forked from jpurcell/birdhouse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbirdhouse.js
805 lines (732 loc) · 22.2 KB
/
birdhouse.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
// --------------------------------------------------------
// birdhouse.js
//
// BirdHouse is a Titanium Developer plugin for
// authenticating and sending API calls to Twitter.
//
// Author: Joseph D. Purcell, iEntry Inc.
// Version: 0.5
// Modified: April 2011
// --------------------------------------------------------
// INCLUDES
// iphone requires complete path
if (Ti.Platform.osname=='iphone') {
Ti.include('lib/oauth.js');
Ti.include('lib/sha1.js');
}
// android will search the current directory for files
else {
Ti.include('oauth.js');
Ti.include('sha1.js');
}
// THE CLASS
function BirdHouse(params) {
// --------------------------------------------------------
// ==================== PRIVATE ===========================
// --------------------------------------------------------
// VARIABLES
var cfg = {
// user config
oauth_consumer_key: "",
consumer_secret: "",
// system config
oauth_version: "1.0",
oauth_token: "",
oauth_signature_method: "HMAC-SHA1",
request_token: "",
request_token_secret: "",
request_verifier: "",
access_token: "",
access_token_secret: "",
callback_url: ""
};
var accessor = {
consumerSecret: cfg.consumer_secret,
tokenSecret : cfg.access_token_secret
};
var authorized = false;
// --------------------------------------------------------
// set_message
//
// Creates a message to send to the Twitter service with
// the given parameters, and adds the consumer key,
// signature method, timestamp, and nonce.
//
// In Parameters:
// url (String) - the url to send the message to
// method (String) - 'POST' or 'GET'
// params (String) - parameters to add to the
// message in URL form, i.e. var1=2&var2=3
//
// Returns:
// message (Array) - the message parameters to send
// to Twitter
// --------------------------------------------------------
function set_message(url, method, params) {
var message = {
action: url,
method: (method=='GET') ? method : 'POST',
parameters: (params!=null) ? OAuth.decodeForm(params) : []
};
message.parameters.push(['oauth_consumer_key', cfg.oauth_consumer_key]);
message.parameters.push(['oauth_signature_method', cfg.oauth_signature_method]);
message.parameters.push(["oauth_timestamp", OAuth.timestamp().toFixed(0)]);
message.parameters.push(["oauth_nonce", OAuth.nonce(42)]);
message.parameters.push(["oauth_version", "1.0"]);
return message;
}
// --------------------------------------------------------
// get_request_token
//
// Sets the request token and token secret.
//
// In Parameters:
// callback (Function) - a function to call after
// the user has been authorized; note that it won't
// be executed until get_access_token()
// --------------------------------------------------------
function get_request_token(callback) {
var url = 'https://api.twitter.com/oauth/request_token';
var params = (cfg.callback_url!="")?'oauth_callback='+escape(cfg.callback_url):'';
api(url,'POST',params,function(resp){
if (resp!=false) {
var responseParams = OAuth.getParameterMap(resp);
cfg.request_token = responseParams['oauth_token'];
cfg.request_token_secret = responseParams['oauth_token_secret'];
get_request_verifier(callback);
}
},false,true,false);
}
// --------------------------------------------------------
// get_request_verifier
//
// Sets the request verifier. There is no reason to call
// this unless you have the request token and token secret.
// In fact, it should only be called from get_request_token()
// for that very reason.
//
// In Parameters:
// callback (Function) - a function to call after
// the user has been authorized; note that it won't
// be executed until get_access_token()
// --------------------------------------------------------
function get_request_verifier(callback) {
var url = "http://api.twitter.com/oauth/authorize?oauth_token="+cfg.request_token;
var webView = Ti.UI.createWebView({
url: url,
scalesPageToFit: true,
touchEnabled: true,
top:0,
backgroundColor: '#FFF'
});
var request_token = "";
var url_base = "";
var params = "";
var compareUrl = ""; // used for iOS
var win = Ti.UI.createWindow({
top: 0,
modal: true,
fullscreen: true
});
var init = true;
var allow = false;
var title = '';
// add the webview to the window and open the window
win.add(webView);
win.open();
webView.addEventListener('load',function(e){
title = webView.evalJS("document.title");
// the first time load, ignore
if (init) {
init = false
}
// the second load they have clicked allow or deny
else {
// listen for the tokenses if "allow" was clicked
if (allow) {
// success!
params = "";
var parts = (e.url).replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
params = params + m;
if (key=='oauth_verifier') {
cfg.request_verifier = value;
}
});
if (cfg.request_verifier!="") {
// my attempt at making sure the stupid webview dies
webView.stopLoading();
win.remove(webView);
win.close();
get_access_token(callback);
return true; // we are done here
}
}
// find out what the user is clicking on
else {
// user is creating a new account (goes to a suspended page if clicked second time)
// just kill the auth process and say "go do this somewhere else"
if ((e.url).search('account')!=-1 || (e.url).search('suspended')!=-1) {
webView.stopLoading();
win.remove(webView);
win.close();
if(typeof(callback)=='function'){
callback(false);
}
return false;
}
// access denied was clicked
else if ((webView.evalJS("document.title")).search('Redirect')==-1) {
webView.stopLoading();
win.remove(webView);
win.close();
if(typeof(callback)=='function'){
callback(false);
}
return false;
}
// allow access was clicked
else {
// note that we can skip the current page, because the page
// is a page on Twitter with a javscript (or PHP) redirect
// when webView load fires again, allow will be true
// and we will extract the tokenses
allow = true;
}
}
}
});
}
// --------------------------------------------------------
// get_access_token
//
// Trades the request token, token secret, and verifier
// for a user's access token.
//
// In Parameters:
// callback (Function) - a function to call after
// the user has been authorized; this is where
// it will get executed after being authorized
// --------------------------------------------------------
function get_access_token(callback) {
var url = 'https://api.twitter.com/oauth/access_token';
api(url,'POST','oauth_token='+cfg.request_token+'&oauth_verifier='+cfg.request_verifier,function(resp){
if (resp!=false) {
var responseParams = OAuth.getParameterMap(resp);
cfg.access_token = responseParams['oauth_token'];
cfg.access_token_secret = responseParams['oauth_token_secret'];
cfg.user_id = responseParams['user_id'];
cfg.screen_name = responseParams['screen_name'];
accessor.tokenSecret = cfg.access_token_secret;
save_access_token();
authorized = load_access_token();
// execute the callback function
if(typeof(callback)=='function'){
callback(true);
}
} else {
// execute the callback function
if(typeof(callback)=='function'){
callback(false);
}
}
},false,true,false);
}
// --------------------------------------------------------
// load_access_token
//
// Loads the access token and token secret from
// 'twitter.config' to the class configuration.
// --------------------------------------------------------
function load_access_token() {
// try to find file
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'twitter.config');
if (!file.exists()) {
return false;
}
// try to read file
var contents = file.read();
if (contents == null) {
return false;
}
// try to parse file into json
try {
var config = JSON.parse(contents.text);
} catch(e) {
return false;
}
// set config
if (config.access_token) {
cfg.access_token = config.access_token;
}
if (config.access_token_secret) {
cfg.access_token_secret = config.access_token_secret;
accessor.tokenSecret = cfg.access_token_secret;
}
return true;
}
// --------------------------------------------------------
// save_access_token
//
// Writes the access token and token secret to
// 'twitter.config'. Saving the config in a file instead
// of using Ti.App.Property jazz allows the config to
// stay around even if the app has been recompiled.
// --------------------------------------------------------
function save_access_token() {
// get file if it exists
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'twitter.config');
// create file if it doesn't exist
if (file == null) {
file = Ti.Filesystem.createFile(Ti.Filesystem.applicationDataDirectory, 'twitter.config');
}
// write config
var config = {
access_token: cfg.access_token,
access_token_secret: cfg.access_token_secret
};
file.write(JSON.stringify(config));
}
// --------------------------------------------------------
// api
//
// Makes a Twitter API call to the given URL by the
// specified method with the given parameters.
//
// In Parameters:
// url (String) - the url to send the XHR to
// method (String) - POST or GET
// params (String) - the parameters to send in URL
// form
// callback (Function) - after execution, call
// this function and send the XHR data to it
// auth (Bool) - whether or not to force auth
// setUrlParams (Bool) - set the params in the URL
// setHeader (Bool) - set "Authorization" HTML header
//
// Notes:
// - the setUrlParams and setHeader should only need
// to be set whenever getting request tokens; values
// should be 'true' and 'false' respectively
// - take advantage of the callback function
//
// Returns: false on failure and the responseText on
// success.
// --------------------------------------------------------
function api(url, method, params, callback, auth, setUrlParams, setHeader) {
var finalUrl = '';
// authorize user if not authorized, and call this in the callback
if (!authorized && (typeof(auth)=='undefined' || auth===true)) {
authorize(function(retval){
if (!retval) {
// we have returned from authorizing, but auth is false, so return false & dont execute API
// execute the callback function
if (typeof(callback)=='function') {
callback(false);
}
return false;
} else {
// fn-api: we have returned from authorizing & we are authorized!
api(url,method,params,callback,auth);
}
});
}
// user is authorized so execute API
else {
// VALIDATE INPUT
if (method!="POST" && method!="GET") {
return false;
}
if (params==null || typeof(params)=="undefined") {
params = "";
}
// VARIABLES
var initparams = params;
// set params
if (params!=null) {
params = params + "&";
}
if (cfg.access_token!='') {
params = params + "oauth_token="+cfg.access_token;
}
// set & sign the message
var message = set_message(url, method, params);
OAuth.SignatureMethod.sign(message, accessor);
// set the URL to send request to
// if we are getting request tokens, all params have to be set in URL
if (typeof(setUrlParams)!='undefined' && setUrlParams==true) {
finalUrl = OAuth.addToURL(message.action, message.parameters);
}
// for all other requests only custom params need set in the URL
else {
finalUrl = OAuth.addToURL(message.action, initparams);
}
var XHR = Ti.Network.createHTTPClient();
// on success, grab the request token
XHR.onload = function() {
// execute the callback function
if (typeof(callback)=='function') {
callback(XHR.responseText);
}
return XHR.responseText;
};
// on error, show message
XHR.onerror = function(e) {
// access token and token secret are wrong
return false;
}
XHR.open(method, finalUrl, false);
// if we are getting request tokens do not set the HTML header
if (typeof(setHeader)=='undefined' || setHeader==true) {
var init = true;
var header = "OAuth ";
for (var i=0; i<message.parameters.length; i++) {
if (init) {
init = false;
} else {
header = header + ",";
}
header = header + message.parameters[i][0] + '="' + escape(message.parameters[i][1]) + '"';
}
XHR.setRequestHeader("Authorization", header);
}
XHR.send();
}
}
// --------------------------------------------------------
// tweet
//
// Opens a tweet dialog box for the user to make a tweet
// to their page after checking if the user is authorized
// with the app. If the user is unauthorized, the
// authorization process will be initiated first.
//
// In Parameters:
// text (String) - the default text for the text area
// callback (Function) - function to call after XHR
// --------------------------------------------------------
function tweet(text,callback) {
// VALIDATE INPUT
// just in case someone only wants to send a callback
if (typeof(text)=='function' && typeof(callback)=='undefined') {
callback = text;
text = '';
}
if (typeof(text)=='undefined') {
text = '';
}
var obj = this;
obj.mytweet = text;
if (authorized === false) {
authorize(function(resp){
if (resp) {
obj.tweet(obj.mytweet);
return true;
} else {
// execute the callback function
if (typeof(callback)=='function') {
callback(false);
}
return false;
}
});
} else {
var chars = (typeof(text)!='undefined' && text!=null)?text.length:0;
var winBG = Titanium.UI.createWindow({
backgroundColor:'#000',
opacity:0.60
});
// the UI window looks completely different on iPhone vs. Android
// iPhone UI
if (Ti.Platform.osname=='iphone') {
var winTW = Titanium.UI.createWindow({
height:((Ti.Platform.displayCaps.platformHeight*0.5)-15), // half because the keyboard takes up half
width:(Ti.Platform.displayCaps.platformWidth-20),
top:10,
right:10,
left:10,
borderColor:'#224466',
borderWidth:3,
backgroundColor:'#559abb',
borderRadius:3.0
});
var tweet = Ti.UI.createTextArea({
value:text,
height:((Ti.Platform.displayCaps.platformHeight*0.5)-100),
width:(Ti.Platform.displayCaps.platformWidth-48),
font:{fontSize:16},
top:14,
left:14,
right:14
});
var btnTW = Ti.UI.createButton({
title:'Tweet!',
width:100,
height:30,
top:((Ti.Platform.displayCaps.platformHeight*0.5)-75),
right:24
});
var btnCancel = Ti.UI.createButton({
title:'Cancel',
width:100,
height:30,
top:((Ti.Platform.displayCaps.platformHeight*0.5)-75),
left:24
});
var charcount = Ti.UI.createLabel({
top:((Ti.Platform.displayCaps.platformHeight*0.5)-55),
left:(Ti.Platform.displayCaps.platformWidth-60), // 30 px from right side,
color:'#FFF',
text:(parseInt((140-chars))+'')
});
}
// Android UI
else {
var winTW = Titanium.UI.createWindow({
height:264,
top:10,
right:10,
left:10,
borderColor:'#224466',
borderWidth:3,
backgroundColor:'#559abb',
borderRadius:3.0
});
var tweet = Ti.UI.createTextArea({
value:text,
height:160,
top:14,
left:14,
right:14
});
var btnTW = Ti.UI.createButton({
title:'Tweet',
width:100,
top:182,
right:24
});
var btnCancel = Ti.UI.createButton({
title:'Cancel',
width:100,
top:182,
left:24
});
var charcount = Ti.UI.createLabel({
bottom:10,
right:14,
color:'#FFF',
text:(parseInt((140-chars))+'')
});
}
tweet.addEventListener('change',function(e) {
chars = (140-e.value.length);
if (chars<11) {
if (charcount.color!='#D40D12') {
charcount.color = '#D40D12';
}
} else if (chars<20) {
if (charcount.color!='#5C0002') {
charcount.color = '#5C0002';
}
} else {
if (charcount.color!='#FFF') {
charcount.color = '#FFF';
}
}
charcount.text = parseInt(chars)+'';
});
btnTW.addEventListener('click',function() {
var retval = send_tweet("status="+escape(tweet.value));
if (retval===false) {
var alertDialog = Titanium.UI.createAlertDialog({
title: 'System Message',
buttonNames: ['OK']
});
alertDialog.message = "Tweet failed to send!";
// execute the callback function
if (typeof(callback)=='function') {
callback(false);
}
return false;
} else {
// hide the keyboard on Android because it doesn't automatically
if (Ti.Platform.osname=='android') {
Titanium.UI.Android.hideSoftKeyboard();
}
// execute the callback function
if (typeof(callback)=='function') {
callback(false);
}
winBG.close();
winTW.close();
return true;
}
});
btnCancel.addEventListener('click',function() {
// hide the keyboard on Android because it doesn't automatically
if (Ti.Platform.osname=='android') {
Titanium.UI.Android.hideSoftKeyboard();
}
winBG.close();
winTW.close();
});
winTW.add(charcount);
winTW.add(tweet);
winTW.add(btnTW);
winTW.add(btnCancel);
winBG.open();
winTW.open();
}
}
// --------------------------------------------------------
// send_tweet
//
// Makes an API call to Twitter to post a tweet.
//
// In Parameters:
// params (String) - the string of optional and
// required parameters in url form
// --------------------------------------------------------
function send_tweet(params) {
api('http://api.twitter.com/1/statuses/update.json','POST',params,function(resp){
if (resp!=false) {
return true;
} else {
return false;
}
});
}
// --------------------------------------------------------
// get_tweets
//
// Makes a TWitter API call to get tweets from the friends
// timeline.
//
// In Parameters:
// params (String) - the string of optional and
// required parameters in url form
// callback (Function) - function to call after XHR
// --------------------------------------------------------
function get_tweets(params,callback) {
// just in case someone only wants to send a callback
if (typeof(params)=='function' && typeof(callback)=='undefined') {
callback = params;
params = '';
}
api("https://api.twitter.com/1/statuses/friends_timeline.json","GET",params,function(tweets){
try {
// parse the JSON, because there isn't a case where you want a string instead of obj returned
tweets = JSON.parse(tweets);
} catch (e) {
tweets = false;
}
// execute the callback function
if(typeof(callback)=='function'){
callback(tweets);
}
return tweets;
})
}
// --------------------------------------------------------
// authorize
//
// The whole authorization sequence begins with
// get_request_token(), which calls get_request_verifier()
// which finally calls get_access_token() which then
// saves the token in a file.
//
// In Parameters:
// callback (Function) - a function to call after
// the user has been authorized; note that it won't
// be executed until get_access_token(), unless we
// are already authorized, and we will call it here
//
// Returns: true if the user is authorized, else false
// --------------------------------------------------------
function authorize(callback) {
if (!authorized) {
get_request_token(callback); // get_request_token or a function it calls will call callback
} else {
var alertDialog = Titanium.UI.createAlertDialog({
title: 'Error Message',
message: 'You are already authorized!',
buttonNames: ['Schweet!']
});
alertDialog.show();
// execute the callback function
if(typeof(callback)=='function'){
callback(authorized);
}
}
return authorized;
}
// --------------------------------------------------------
// deauthorize
//
// Delete the stored access token file, delete the tokens
// from the config and accessor, and set authorized to
// load_access_token() which should return false since
// we deleted the file, thus resulting in a deauthroized
// state.
//
// In Parameters:
// callback (Function) - function to call after
// user is deauthorized
//
// Returns: true if the user is deauthorized, else false
// --------------------------------------------------------
function deauthorize(callback) {
if (authorized) {
// delete the config file
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'twitter.config');
file.deleteFile();
// check to make sure it was deleted by re-setting authorized
authorized = load_access_token();
// reset config
accessor.tokenSecret = "";
cfg.access_token = "";
cfg.access_token_secret = "";
cfg.request_verifier = "";
// execute the callback function
if(typeof(callback)=='function'){
callback(!authorized);
}
} else {
var alertDialog = Titanium.UI.createAlertDialog({
title: 'Error Message',
message: 'You are already deauthorized!',
buttonNames: ['Oh, OK']
});
alertDialog.show();
// execute the callback function
if(typeof(callback)=='function'){
callback(!authorized);
}
}
return !authorized;
}
// --------------------------------------------------------
// ===================== PUBLIC ===========================
// --------------------------------------------------------
this.authorize = authorize;
this.deauthorize = deauthorize;
this.api = api;
this.authorized = function() { return authorized; }
this.get_tweets = get_tweets;
this.tweet = tweet;
// --------------------------------------------------------
// =================== INITIALIZE =========================
// --------------------------------------------------------
if (typeof params == 'object') {
if (params.consumer_key != undefined) {
cfg.oauth_consumer_key = params.consumer_key;
}
if (params.consumer_secret != undefined) {
cfg.consumer_secret = params.consumer_secret;
accessor.consumerSecret = cfg.consumer_secret;
}
if (params.callback_url != undefined) {
cfg.callback_url = params.callback_url;
}
}
authorized = load_access_token(); // load the token on startup to see if authorized
};