Sean Kelley
Posts: 0
Joined: Thu Oct 11, 2012 2:25 pm

twitter tutorial- javascript

I am trying to get through the twitter tutorials:
http://docs.appery.io/tutorials/creat...
http://docs.appery.io/tutorials/build...

I do not want to search- just send. I appear to be stuck at the point where the two tutorials merge code.

On first page at Mapping the OAuth2Service step 2 you provide basic javascript for TwitSearchGlobal. I am doing something wrong when I try to add to that the code from tutorial #2. No matter what I do I get errors. Is it possible to provide a combined code for the module TwitSearchGlobal ?

Kateryna Grynko
Posts: 0
Joined: Thu Nov 15, 2012 9:13 am

twitter tutorial- javascript

Hi Sean,

Please share the app with a href="mailto:support@appery.io" rel="nofollow"support@appery.io/a.
What is the combined code you need? What did you change?

Sean Kelley
Posts: 0
Joined: Thu Oct 11, 2012 2:25 pm

twitter tutorial- javascript

Hi
I can share, but basically if you follow through the tutorials its a bit confusing. If you start with tutorial to send tweets:
http://docs.appery.io/tutorials/build...

It says you must use code from another tutorial:
http://docs.appery.io/tutorials/creat...

In tutorial on sending tweets it says ' Add Js' and proceeds to show 4 blocks of additional code to ad. By copy and pasting the code, I get syntax error.

My understanding of JS is a little weak and the tutorial code does not display well in my browser, but here is the final TwitterSearchJS module I came up with.
The first line of new code I added, gives me a syntax error:

//first snippet of new code added from tutorial 2
SHA1Lib = {

error in console is:
Uncaught SyntaxError: Unexpected identifier
for the above line

code
TwitSearchGlobal = {

Code: Select all

 bearerToken : "", 

     encodeBase64 : function ( data ) {// Encodes data with MIME base64 

// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Bayron Guevara
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=&quot
var o1, o2, o3, h1, h2, h3, h4, bits, i=0, enc='';

Code: Select all

     do {// pack three octets into four hexes 
         o1 = data.charCodeAt(i++); 
         o2 = data.charCodeAt(i++); 
         o3 = data.charCodeAt(i++); 

         bits = o1<<16 | o2<<8 | o3; 
                     h1 = bits>>18 & 0x3f; 
         h2 = bits>>12 & 0x3f; 
         h3 = bits>>6 & 0x3f; 
         h4 = bits & 0x3f;&#47;&#47; use hexes to index into b64, and append result to encoded string 
             enc += b64&#46;charAt(h1) + b64&#46;charAt(h2) + b64&#46;charAt(h3) + b64&#46;charAt(h4); 
     } while (i < data&#46;length); 

     switch( data&#46;length % 3 ){ 
         case 1: 
             enc = enc&#46;slice(0, -2) + '=='; 
             break; 
         case 2: 
             enc = enc&#46;slice(0, -1) + '='; 
             break; 
     } 
     return enc; 
 }, 

 beforeSearchTwit : function () { 
     if (this&#46;bearerToken == ""){&#47;&#47; get bearer token and after that call searchTwit 
            OAuth2DS&#46;execute({}); 
     } else { 
            SearchDS&#46;execute({});     
     }     
 } 

&#47;&#47;first snippet of new code added from tutorial 2
SHA1Lib = {
str2binb : function (str){
var bin = Array();
for(var i = 0; i < str&#46;length * 8; i += 8){
bin[i>>5] |= (str&#46;charCodeAt(i &#47; 8) & 255) << (24 - i%32);
}
return bin;
},

Code: Select all

 sha1_ft : function (t, b, c, d){ 
 if(t < 20) return (b & c) | ((~b) & d); 
 if(t < 40) return b ^ c ^ d; 
 if(t < 60) return (b & c) | (b & d) | (c & d); 
 return b ^ c ^ d; 

},

Code: Select all

 sha1_kt : function (t){ 
 return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : 
       (t < 60) ? -1894007588 : -899497514; 

},

Code: Select all

 safe_add : function (x, y){ 
 var lsw = (x & 0xFFFF) + (y & 0xFFFF); 
 var msw = (x >> 16) + (y >> 16) + (lsw >> 16); 
 return (msw << 16) | (lsw & 0xFFFF); 

},

Code: Select all

 core_sha1 : function(x, len){ 
 x[len >> 5] |= 0x80 << (24 - len % 32); 
 x[((len + 64 >> 9) << 4) + 15] = len; 

 var w = Array(80); 
 var a = 1732584193; 
 var b = -271733879; 
 var c = -1732584194; 
 var d = 271733878; 
 var e = -1009589776; 

 for(var i = 0; i < x&#46;length; i += 16){ 
   var olda = a; 
   var oldb = b; 
   var oldc = c; 
   var oldd = d; 
   var olde = e; 

   for(var j = 0; j < 80; j++){ 
      if (j < 16){ 
                 w[j] = x[i + j]; 
             } else { 
                 w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); 
             } 
      var t = this&#46;safe_add(this&#46;safe_add(rol(a, 5), this&#46;sha1_ft(j, b, c, d)), 
                    this&#46;safe_add(this&#46;safe_add(e, w[j]), this&#46;sha1_kt(j))); 
      e = d; 
                     d = c; 
      c = rol(b, 30); 
      b = a; 
      a = t; 
   } 

   a = safe_add(a, olda); 
   b = safe_add(b, oldb); 
   c = safe_add(c, oldc); 
   d = safe_add(d, oldd); 
   e = safe_add(e, olde); 
 } 
 return Array(a, b, c, d, e); 

},

Code: Select all

 core_hmac_sha1 : function (key, data){ 
 var bkey = this&#46;str2binb(key); 
 if(bkey&#46;length > 16) bkey = core_sha1(bkey, key&#46;length * 8); 
 var ipad = Array(16), opad = Array(16); 
 for(var i = 0; i < 16; i++){ 
   ipad[i] = bkey[i] ^ 0x36363636; 
   opad[i] = bkey[i] ^ 0x5C5C5C5C; 
 } 

var hash = core_sha1(ipad&#46;concat(this&#46;str2binb(data)), 512 + data&#46;length * 8);
return core_sha1(opad&#46;concat(hash), 512 + 160);
},

Code: Select all

 binb2b64 : function (binarray) { 
 var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+&#47;'; 
 var str = ''; 
 for(var i = 0; i < binarray&#46;length * 4; i += 3){ 
   var triplet = (((binarray[i >> 2] >> 8*(3 - i%4)) & 0xFF) << 16) 
             | (((binarray[i+1 >> 2] >> 8*(3 - (i+1)%4)) & 0xFF) << 8 ) 
             | ((binarray[i+2 >> 2] >> 8*(3 - (i+2)%4)) & 0xFF); 
   for(var j = 0; j < 4; j++){ 
      if(i*8 + j*6 > binarray&#46;length * 32){ 
                 str += '='; 
           } else { 
                 str += tab&#46;charAt((triplet >> 6*(3-j)) & 0x3F); 
             } 
   } 
 } 
 return str; 

}
}
&#47;&#47;end first snippet

&#47;&#47;start second snippet from tutorial #2
EncodeHelper = {

Code: Select all

 token : "", 
 tokenSecret : "", 

 generateNonce : function () { 
     var nonce = ''; 
     for (var i = 0; i < 8; i++) { 
         var character = Math&#46;floor(Math&#46;random() * 61); 
         nonce += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'&#46;substring(character, character + 1); 
     } 
     return nonce; 
 }, 

 encodeSymbols : function (string){ 
     return encodeURIComponent(string)&#46;replace(&#47;[!'()]&#47;g, escape)&#46;replace(&#47;\*&#47;g, "%2A");   
 }, 

 calcHash : function (key, data) { 
     var hash = SHA1Lib&#46;core_hmac_sha1(key, data); 
     return SHA1Lib&#46;binb2b64(hash); 
 }, 

 getHeader : function (apiUrl, params) { 
     if (typeof params == 'undefined') { 
         var params = {}; 
     } 

&#47;&#47;signParams to generate signature
var signParams = {
oauth_consumer_key: TwitterSearchSettings&#46;consumerKey,
oauth_version: '1&#46;0',
oauth_timestamp: Math&#46;round(new Date()&#46;getTime() &#47; 1000),
oauth_nonce: this&#46;generateNonce(),
oauth_signature_method: 'HMAC-SHA1'
};
if (this&#46;token != ""){
signParams['oauth_token'] = this&#46;token;
}
&#47;&#47; oauthParams contains the parameters for authorization string
var oauthParams = {};
for (var i in signParams) {
oauthParams = signParams;
}
&#47;&#47; add params to generate signature in signParams
for (var key in params) {
var value = params[key];
signParams[key] = this&#46;encodeSymbols(value);
}
var keys = [];
for (var key in signParams) {
keys&#46;push(key);
}
keys&#46;sort();
var signBaseString = '';
for (var i=0; i<keys&#46;length; i++) {
var key = keys;
var value = signParams[key];
signBaseString += key + '=' + value + '&';
}
signBaseString = signBaseString&#46;substring(0, signBaseString&#46;length - 1);
signBaseString = 'POST&' + this&#46;encodeSymbols(apiUrl) + '&' + this&#46;encodeSymbols(signBaseString);
var signingKey = TwitterSearchSettings&#46;consumerKeySecret + '&';
if (this&#46;tokenSecret != ""){
signingKey += this&#46;tokenSecret;
}
var signature = this&#46;calcHash(signingKey, signBaseString);
oauthParams['oauth_signature'] = signature;&#47;&#47; creating authorization string
var authorization = 'OAuth ';
for (var key in oauthParams) {
var value = oauthParams[key];
authorization += key + '="' + this&#46;encodeSymbols(value) + '", ';
}
return authorization&#46;substring(0, authorization&#46;length - 2);
}
}
&#47;&#47;end #2 snippet from tutorial #2

&#47;&#47;start 3rd snippet from tutorial #2
accessTokenExist : false,
handleError : function (message) {
$('[name=errLabel]')&#46;text(message);
},

Code: Select all

 goodMessage : function () { 
     $('[name=sendLabel]')&#46;text('Your message has been sent&#46;');     
 }, 

 clearLabels : function () { 
      $('[name=sendLabel]')&#46;text(''); 
     $('[name=errLabel]')&#46;text(''); 
 }, 

 parseReply : function (reply){ 
     try { 
         if (reply&#46;indexOf('<!--?xml version') === 0){&#47;&#47; XML has got 
             this&#46;handleError(reply&#46;match(&#47;(&#46;*)< 

TwitSearchGlobal = {

Code: Select all

 bearerToken : "", 

     encodeBase64 : function ( data ) {// Encodes data with MIME base64 

// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Bayron Guevara
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i=0, enc='';

Code: Select all

     do {// pack three octets into four hexes 
         o1 = data.charCodeAt(i++); 
         o2 = data.charCodeAt(i++); 
         o3 = data.charCodeAt(i++); 

         bits = o1<<18 & 0x3f; 
         h2 = bits12 & 0x3f; 
         h3 = bits6 & 0x3f; 
         h4 = bits & 0x3f;// use hexes to index into b64, and append result to encoded string 
             enc += b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); 
     } while (i < data.length); 

     switch( data.length % 3 ){ 
         case 1: 
             enc = enc.slice(0, -2) + '=='; 
             break; 
         case 2: 
             enc = enc.slice(0, -1) + '='; 
             break; 
     } 
     return enc; 
 }, 

 beforeSearchTwit : function () { 
     if (this.bearerToken == ""){// get bearer token and after that call searchTwit 
            OAuth2DS.execute({}); 
     } else { 
            SearchDS.execute({});     
     }     
 } 

//first snippet of new code added from tutorial 2
SHA1Lib = {
str2binb : function (str){
var bin = Array();
for(var i = 0; i < str.length * 8; i += 8){
bin[i5] |= (str.charCodeAt(i / 8) & 255) << (24 - i%32);
}
return bin;
},

Code: Select all

 sha1_ft : function (t, b, c, d){ 
 if(t < 20) return (b & c) | ((~b) & d); 
 if(t < 40) return b ^ c ^ d; 
 if(t < 60) return (b & c) | (b & d) | (c & d); 
 return b ^ c ^ d; 

},

Code: Select all

 sha1_kt : function (t){ 
 return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : 
       (t < 60) ? -1894007588 : -899497514; 

},

Code: Select all

 safe_add : function (x, y){ 
 var lsw = (x & 0xFFFF) + (y & 0xFFFF); 
 var msw = (x  16) + (y  16) + (lsw  16); 
 return (msw << 16) | (lsw & 0xFFFF); 

},

Code: Select all

 core_sha1 : function(x, len){ 
 x[len  5] |= 0x80 << (24 - len % 32); 
 x[((len + 64  9) << 4) + 15] = len; 

 var w = Array(80); 
 var a = 1732584193; 
 var b = -271733879; 
 var c = -1732584194; 
 var d = 271733878; 
 var e = -1009589776; 

 for(var i = 0; i < x.length; i += 16){ 
   var olda = a; 
   var oldb = b; 
   var oldc = c; 
   var oldd = d; 
   var olde = e; 

   for(var j = 0; j < 80; j++){ 
      if (j < 16){ 
                 w[j] = x[i + j]; 
             } else { 
                 w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); 
             } 
      var t = this.safe_add(this.safe_add(rol(a, 5), this.sha1_ft(j, b, c, d)), 
                    this.safe_add(this.safe_add(e, w[j]), this.sha1_kt(j))); 
      e = d; 
                     d = c; 
      c = rol(b, 30); 
      b = a; 
      a = t; 
   } 

   a = safe_add(a, olda); 
   b = safe_add(b, oldb); 
   c = safe_add(c, oldc); 
   d = safe_add(d, oldd); 
   e = safe_add(e, olde); 
 } 
 return Array(a, b, c, d, e); 

},

Code: Select all

 core_hmac_sha1 : function (key, data){ 
 var bkey = this.str2binb(key); 
 if(bkey.length  16) bkey = core_sha1(bkey, key.length * 8); 
 var ipad = Array(16), opad = Array(16); 
 for(var i = 0; i < 16; i++){ 
   ipad[i] = bkey[i] ^ 0x36363636; 
   opad[i] = bkey[i] ^ 0x5C5C5C5C; 
 } 

var hash = core_sha1(ipad.concat(this.str2binb(data)), 512 + data.length * 8);
return core_sha1(opad.concat(hash), 512 + 160);
},

Code: Select all

 binb2b64 : function (binarray) { 
 var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; 
 var str = ''; 
 for(var i = 0; i < binarray.length * 4; i += 3){ 
   var triplet = (((binarray[i  2]  8*(3 - i%4)) & 0xFF) << 16) 
             | (((binarray[i+1  2]  8*(3 - (i+1)%4)) & 0xFF) << 8 ) 
             | ((binarray[i+2  2]  8*(3 - (i+2)%4)) & 0xFF); 
   for(var j = 0; j < 4; j++){ 
      if(i*8 + j*6  binarray.length * 32){ 
                 str += '='; 
           } else { 
                 str += tab.charAt((triplet  6*(3-j)) & 0x3F); 
             } 
   } 
 } 
 return str; 

}
}
//end first snippet

//start second snippet from tutorial #2
EncodeHelper = {

Code: Select all

 token : "", 
 tokenSecret : "", 

 generateNonce : function () { 
     var nonce = ''; 
     for (var i = 0; i < 8; i++) { 
         var character = Math.floor(Math.random() * 61); 
         nonce += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.substring(character, character + 1); 
     } 
     return nonce; 
 }, 

 encodeSymbols : function (string){ 
     return encodeURIComponent(string).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");   
 }, 

 calcHash : function (key, data) { 
     var hash = SHA1Lib.core_hmac_sha1(key, data); 
     return SHA1Lib.binb2b64(hash); 
 }, 

 getHeader : function (apiUrl, params) { 
     if (typeof params == 'undefined') { 
         var params = {}; 
     } 

//signParams to generate signature
var signParams = {
oauth_consumer_key: TwitterSearchSettings.consumerKey,
oauth_version: '1.0',
oauth_timestamp: Math.round(new Date().getTime() / 1000),
oauth_nonce: this.generateNonce(),
oauth_signature_method: 'HMAC-SHA1'
};
if (this.token != ""){
signParams['oauth_token'] = this.token;
}
// oauthParams contains the parameters for authorization string
var oauthParams = {};
for (var i in signParams) {
oauthParams = signParams;
}
// add params to generate signature in signParams
for (var key in params) {
var value = params[key];
signParams[key] = this.encodeSymbols(value);
}
var keys = [];
for (var key in signParams) {
keys.push(key);
}
keys.sort();
var signBaseString = '';
for (var i=0; i/)[1]);
return 1;
}
var array = reply.split('&');
var tmp = array[0].split('=',2);
EncodeHelper.token = unescape(tmp[1]);
tmp = array[1].split('=',2);
EncodeHelper.tokenSecret = unescape(tmp[1]);
return 0;
} catch(e) {
this.handleError('Parsing: ' + reply);
return 1;
}
},

Code: Select all

 requestToken : function () { 
     this.clearLabels(); 
     EncodeHelper.token = ""; 
     EncodeHelper.tokenSecret = ""; 
     RequestTokenDS.execute({});     
 },         

 authorizeToken : function (responseText) { 
     if (this.parseReply(responseText) != 0){ 
         return; 
     }     
     try { 
         var authorizeUrl = '[url=https://api.twitter.com/oauth/authorize?oauth_token]https://api.twitter.com/oauth/authori...[/url]=' + EncodeHelper.token; 
         if (window.plugins){//mobileDevice 
             window.plugins.childBrowser.showWebPage(authorizeUrl); 
         } else { // desktop 
             window.open(authorizeUrl); 
         }     
     } catch (err) { 
         this.handleError('Unexpected service error.'); 
     } 
 }, 

 beforeSendTwit : function () { 
     this.clearLabels(); 
     var messText = $('[name=sendInput]').val(); 
     if (messText == ""){ 
         this.handleError('Enter the message to send.'); 
         return; 
     }  

     if (this.accessTokenExist){  
         this.sendTwit(); 
     } else {// get accessToken to this.token 
         var pinCode = $('[name=PINLabel]').val(); 
         if (pinCode == ""){ 
             this.handleError('Enter PIN code.'); 
             return; 
         }     
         AccessTokenDS.execute({});// will call setAccessToken and after that will call sendTwit 
    } 

},

Code: Select all

 setAccessToken : function (responseText) { 
     if (this.parseReply(responseText) != 0){ 
         return; 
     }  
     this.accessTokenExist = true; 
     $('[name=pinGrid]').hide(); 
     this.sendTwit(); 
 },     

 sendTwit : function () { 
        SendDS.execute({}); 
 }, 

 parseError : function (jqXHR) { 
     var text; 
     if (jqXHR.responseText){ 
           try { 
             var obj = jQuery.parseJSON(jqXHR.responseText); 
             text = obj.errors[0].message; 
           } catch(e) { 
             text = jqXHR.statusText; 
           }   
     } else { 
           text = jqXHR.statusText; 
     } 
     this.handleError(text); 
 } 

//end 3rd snippet
//last snippet added
//correct replacement instead of standard from jQuery.

jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = EncodeHelper.encodeSymbols( key ) + "=" + EncodeHelper.encodeSymbols( value );
};

Code: Select all

 // Set traditional to true for jQuery /code
Sean Kelley
Posts: 0
Joined: Thu Oct 11, 2012 2:25 pm

twitter tutorial- javascript

I should also add, that there may be a typo in the tutorial where what is typed does not match screen cap:
http://docs.appery.io/tutorials/build...

At TwitterSend_AccessTokenService

" Create datasource on ‘Data’ tab of TwitterSendScreen.

Click TwitterSendScreen on left panel into pages list, click Data tab.
Select Service datasource, select TwitSend_RequestTokenService and click green button Add.
Rename the datasource to AccessTokenDS"

Illya Stepanov
Posts: 0
Joined: Mon Mar 18, 2013 8:48 am

twitter tutorial- javascript

Thanks Sean - we'll double check it!

Maryna Brodina
Posts: 0
Joined: Thu Apr 05, 2012 7:27 am

twitter tutorial- javascript

Hello! We have an idea to create new Twitter tutorial.
Someone will get back to this post regarding your shared app.

Sean Kelley
Posts: 0
Joined: Thu Oct 11, 2012 2:25 pm

twitter tutorial- javascript

thanks- For whatever its worth, I am not personally interested in searching. I want to allow others to send tweet of app items and also auto send tweet to my account when item gets created in database. It might be nice to see twitter send example with attached photo also :-)

Maryna Brodina
Posts: 0
Joined: Thu Apr 05, 2012 7:27 am

twitter tutorial- javascript

Hello! Sorry for delay, we're working on updating tutorial. Looks like you have a few closing brackets missing. Please try create three separate JS files instead one file with the following content:
1) codeTwitSearchGlobal = {

Code: Select all

 &#47;&#47; private property 

_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+&#47;=",

bearerToken : "",

&#47;&#47; public method for encoding
encode : function (input) {
var output = "&quot
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;

Code: Select all

  input = TwitSearchGlobal&#46;_utf8_encode(input); 

  while (i < input&#46;length) { 

      chr1 = input&#46;charCodeAt(i++); 
      chr2 = input&#46;charCodeAt(i++); 
      chr3 = input&#46;charCodeAt(i++); 

      enc1 = chr1 >> 2; 
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); 
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); 
      enc4 = chr3 & 63; 

      if (isNaN(chr2)) { 
          enc3 = enc4 = 64; 
      } else if (isNaN(chr3)) { 
          enc4 = 64; 
      } 

      output = output + 
      this&#46;_keyStr&#46;charAt(enc1) + this&#46;_keyStr&#46;charAt(enc2) + 
      this&#46;_keyStr&#46;charAt(enc3) + this&#46;_keyStr&#46;charAt(enc4); 

  } 

  return output; 

},

&#47;&#47; private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string&#46;replace(&#47;\r\n&#47;g,"\n");
var utftext = "&quot

Code: Select all

  for (var n = 0; n < string&#46;length; n++) { 

      var c = string&#46;charCodeAt(n); 

      if (c < 128) { 
          utftext += String&#46;fromCharCode(c); 
      } 
      else if((c > 127) && (c < 2048)) { 
          utftext += String&#46;fromCharCode((c >> 6) | 192); 
          utftext += String&#46;fromCharCode((c & 63) | 128); 
      } 
      else { 
          utftext += String&#46;fromCharCode((c >> 12) | 224); 
          utftext += String&#46;fromCharCode(((c >> 6) & 63) | 128); 
          utftext += String&#46;fromCharCode((c & 63) | 128); 
      } 
  } 

  return utftext; 

},

Code: Select all

 beforeSearchTwit : function () { 
     if (this&#46;bearerToken == ""){  &#47;&#47; get bearer token and after that call searchTwit 
         OAuth2DS&#46;execute({}); 
     } else { 
         SearchDS&#46;execute({});     
     }     
 }, 

 accessTokenExist : false, 

 handleError : function (message) { 
     $('[name=errLabel]')&#46;text(message); 
 }, 

 goodMessage : function () { 
  $('[name=sendLabel]')&#46;text('Your message has been sent&#46;');     
 }, 

 clearLabels : function () { 
   $('[name=sendLabel]')&#46;text(''); 
     $('[name=errLabel]')&#46;text(''); 
 }, 

 parseReply : function (reply){ 
     try { 
         if (reply&#46;indexOf('<!--?xml version') === 0){ &#47;&#47; XML has got 
             this&#46;handleError(reply&#46;match(&#47;(&#46;*)<TwitSearchGlobal = { 

 // private property 

_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

bearerToken : "",

// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;

Code: Select all

  input = TwitSearchGlobal._utf8_encode(input); 

  while (i < input.length) { 

      chr1 = input.charCodeAt(i++); 
      chr2 = input.charCodeAt(i++); 
      chr3 = input.charCodeAt(i++); 

      enc1 = chr1  2; 
      enc2 = ((chr1 & 3) << 4) | (chr2  4); 
      enc3 = ((chr2 & 15) << 2) | (chr3  6); 
      enc4 = chr3 & 63; 

      if (isNaN(chr2)) { 
          enc3 = enc4 = 64; 
      } else if (isNaN(chr3)) { 
          enc4 = 64; 
      } 

      output = output + 
      this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + 
      this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); 

  } 

  return output; 

},

// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";

Code: Select all

  for (var n = 0; n < string.length; n++) { 

      var c = string.charCodeAt(n); 

      if (c < 128) { 
          utftext += String.fromCharCode(c); 
      } 
      else if((c  127) && (c < 2048)) { 
          utftext += String.fromCharCode((c  6) | 192); 
          utftext += String.fromCharCode((c & 63) | 128); 
      } 
      else { 
          utftext += String.fromCharCode((c  12) | 224); 
          utftext += String.fromCharCode(((c  6) & 63) | 128); 
          utftext += String.fromCharCode((c & 63) | 128); 
      } 
  } 

  return utftext; 

},

Code: Select all

 beforeSearchTwit : function () { 
     if (this.bearerToken == ""){  // get bearer token and after that call searchTwit 
         OAuth2DS.execute({}); 
     } else { 
         SearchDS.execute({});     
     }     
 }, 

 accessTokenExist : false, 

 handleError : function (message) { 
     $('[name=errLabel]').text(message); 
 }, 

 goodMessage : function () { 
  $('[name=sendLabel]').text('Your message has been sent.');     
 }, 

 clearLabels : function () { 
   $('[name=sendLabel]').text(''); 
     $('[name=errLabel]').text(''); 
 }, 

 parseReply : function (reply){ 
     try { 
         if (reply.indexOf('?xml version') === 0){ // XML has got 
             this.handleError(reply.match(/(.*)/)[1]); 
          return 1; 
         }     
         var array = reply.split('&'); 
         var tmp = array[0].split('=',2); 
EncodeHelper.token = unescape(tmp[1]); 
         tmp = array[1].split('=',2); 
         EncodeHelper.tokenSecret = unescape(tmp[1]); 
         return 0; 
     } catch(e) { 
      this.handleError('Parsing: ' + reply);  
         return 1; 
     } 
 },  

 requestToken : function () { 
     this.clearLabels(); 
     EncodeHelper.token = ""; 
     EncodeHelper.tokenSecret = ""; 

RequestTokenDS.execute({});
},

Code: Select all

 authorizeToken : function (responseText) { 
     //alert('responseText en authorizeToken: ' + responseText); 
     if (this.parseReply(responseText) != 0){ 
         return; 
     }     
     try { 
         var authorizeUrl = '[url=https://api.twitter.com/oauth/authorize?oauth_token]https://api.twitter.com/oauth/authori...[/url]=' + EncodeHelper.token; 
         if (window.plugins){ //mobileDevice 
 window.plugins.childBrowser.showWebPage(authorizeUrl); 
         } else { // desktop 
             window.open(authorizeUrl); 
         }     

} catch (err) {
this.handleError('Unexpected service error.');
}
},

Code: Select all

 beforeSendTwit : function () { 
     this.clearLabels(); 
     var messText = $('[name=sendInput]').val(); 
     if (messText == ""){ 
         this.handleError('Enter the message to send.'); 
         return; 
     } 

     if (this.accessTokenExist){  
         this.sendTwit(); 
     } else { // get accessToken to this.token 
         var pinCode = $('[name=PINInput]').val(); 
         if (pinCode == ""){ 
             this.handleError('Enter PIN code.'); 
             return; 
         } 
         //alert('pinCode: ' +pinCode); 
         AccessTokenDS.execute({}); // will call setAccessToken and after that will call sendTwit 
     } 

},

Code: Select all

 setAccessToken : function (responseText) { 

//alert('responseText en setAccessToken: ' + responseText);
if (this.parseReply(responseText) != 0){
return;
}
this.accessTokenExist = true;
$('[name=pinGrid]').hide();
this.sendTwit();
},

Code: Select all

 sendTwit : function () { 
     SendDS.execute({}); 
 }, 

 parseError : function (jqXHR) { 
     var text; 
     if (jqXHR.responseText){ 
  try { 
 var obj = jQuery.parseJSON(jqXHR.responseText); 
 text = obj.errors[0].message; 
  } catch(e) { 
    text = jqXHR.statusText; 
  }   

} else {
text = jqXHR.statusText;
}
this.handleError(text);
}

}
#47;error>&#47;)[1]);
return 1;
}
var array = reply&#46;split('&');
var tmp = array[0]&#46;split('=',2);
EncodeHelper&#46;token = unescape(tmp[1]);
tmp = array[1]&#46;split('=',2);
EncodeHelper&#46;tokenSecret = unescape(tmp[1]);
return 0;
} catch(e) {
this&#46;handleError('Parsing: ' + reply);
return 1;
}
},

Code: Select all

 requestToken : function () { 
     this&#46;clearLabels(); 
     EncodeHelper&#46;token = "&quot 
     EncodeHelper&#46;tokenSecret = "&quot 

RequestTokenDS&#46;execute({});
},

Code: Select all

 authorizeToken : function (responseText) { 
     &#47;&#47;alert('responseText en authorizeToken: ' + responseText); 
     if (this&#46;parseReply(responseText) != 0){ 
         return; 
     }     
     try { 
         var authorizeUrl = 'https:&#47;&#47;api&#46;twitter&#46;com&#47;oauth&#47;authorize?oauth_token=' + EncodeHelper&#46;token; 
         if (window&#46;plugins){ &#47;&#47;mobileDevice 
 window&#46;plugins&#46;childBrowser&#46;showWebPage(authorizeUrl); 
         } else { &#47;&#47; desktop 
             window&#46;open(authorizeUrl); 
         }     

} catch (err) {
this&#46;handleError('Unexpected service error&#46;');
}
},

Code: Select all

 beforeSendTwit : function () { 
     this&#46;clearLabels(); 
     var messText = $('[name=sendInput]')&#46;val(); 
     if (messText == ""){ 
         this&#46;handleError('Enter the message to send&#46;'); 
         return; 
     } 

     if (this&#46;accessTokenExist){  
         this&#46;sendTwit(); 
     } else { &#47;&#47; get accessToken to this&#46;token 
         var pinCode = $('[name=PINInput]')&#46;val(); 
         if (pinCode == ""){ 
             this&#46;handleError('Enter PIN code&#46;'); 
             return; 
         } 
         &#47;&#47;alert('pinCode: ' +pinCode); 
         AccessTokenDS&#46;execute({}); &#47;&#47; will call setAccessToken and after that will call sendTwit 
     } 

},

Code: Select all

 setAccessToken : function (responseText) { 

&#47;&#47;alert('responseText en setAccessToken: ' + responseText);
if (this&#46;parseReply(responseText) != 0){
return;
}
this&#46;accessTokenExist = true;
$('[name=pinGrid]')&#46;hide();
this&#46;sendTwit();
},

Code: Select all

 sendTwit : function () { 
     SendDS&#46;execute({}); 
 }, 

 parseError : function (jqXHR) { 
     var text; 
     if (jqXHR&#46;responseText){ 
  try { 
 var obj = jQuery&#46;parseJSON(jqXHR&#46;responseText); 
 text = obj&#46;errors[0]&#46;message; 
  } catch(e) { 
    text = jqXHR&#46;statusText; 
  }   

} else {
text = jqXHR&#46;statusText;
}
this&#46;handleError(text);
}

}
/code
2) codeSHA1Lib = {
str2binb : function (str){
var bin = Array();
for(var i = 0; i < str&#46;length * 8; i += 8){
bin[i>>5] |= (str&#46;charCodeAt(i &#47; 8) & 255) << (24 - i%32);
}
return bin;
},

Code: Select all

 sha1_ft : function (t, b, c, d){ 
 if(t < 20) return (b & c) | ((~b) & d); 
 if(t < 40) return b ^ c ^ d; 
 if(t < 60) return (b & c) | (b & d) | (c & d); 
 return b ^ c ^ d; 

},

Code: Select all

 sha1_kt : function (t){ 
 return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : 
       (t < 60) ? -1894007588 : -899497514; 

},

Code: Select all

 safe_add : function (x, y){ 
 var lsw = (x & 0xFFFF) + (y & 0xFFFF); 
 var msw = (x >> 16) + (y >> 16) + (lsw >> 16); 
 return (msw << 16) | (lsw & 0xFFFF); 

},

Code: Select all

 core_sha1 : function(x, len){ 
 x[len >> 5] |= 0x80 << (24 - len % 32); 
 x[((len + 64 >> 9) << 4) + 15] = len; 

 var w = Array(80); 
 var a = 1732584193; 
 var b = -271733879; 
 var c = -1732584194; 
 var d = 271733878; 
 var e = -1009589776; 

 for(var i = 0; i < x&#46;length; i += 16){ 
   var olda = a; 
   var oldb = b; 
   var oldc = c; 
   var oldd = d; 
   var olde = e; 

   for(var j = 0; j < 80; j++){ 
      if (j < 16){ 
                 w[j] = x[i + j]; 
             } else { 
                 w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1); 
             } 
      var t = this&#46;safe_add(this&#46;safe_add(rol(a, 5), this&#46;sha1_ft(j, b, c, d)), 
                    this&#46;safe_add(this&#46;safe_add(e, w[j]), this&#46;sha1_kt(j))); 
      e = d; 
                     d = c; 
      c = rol(b, 30); 
      b = a; 
      a = t; 
   } 

   a = safe_add(a, olda); 
   b = safe_add(b, oldb); 
   c = safe_add(c, oldc); 
   d = safe_add(d, oldd); 
   e = safe_add(e, olde); 
 } 
 return Array(a, b, c, d, e); 

},

Code: Select all

 core_hmac_sha1 : function (key, data){ 
 var bkey = this&#46;str2binb(key); 
 if(bkey&#46;length > 16) bkey = core_sha1(bkey, key&#46;length * 8); 
 var ipad = Array(16), opad = Array(16); 
 for(var i = 0; i < 16; i++){ 
   ipad[i] = bkey[i] ^ 0x36363636; 
   opad[i] = bkey[i] ^ 0x5C5C5C5C; 
 } 

var hash = core_sha1(ipad&#46;concat(this&#46;str2binb(data)), 512 + data&#46;length * 8);
return core_sha1(opad&#46;concat(hash), 512 + 160);
},

Code: Select all

 binb2b64 : function (binarray) { 
 var tab = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+&#47;'; 
 var str = ''; 
 for(var i = 0; i < binarray&#46;length * 4; i += 3){ 
   var triplet = (((binarray[i >> 2] >> 8*(3 - i%4)) & 0xFF) << 16) 
             | (((binarray[i+1 >> 2] >> 8*(3 - (i+1)%4)) & 0xFF) << 8 ) 
             | ((binarray[i+2 >> 2] >> 8*(3 - (i+2)%4)) & 0xFF); 
   for(var j = 0; j < 4; j++){ 
      if(i*8 + j*6 > binarray&#46;length * 32){ 
                 str += '='; 
           } else { 
                 str += tab&#46;charAt((triplet >> 6*(3-j)) & 0x3F); 
             } 
   } 
 } 
 return str; 

}
}

EncodeHelper = {

Code: Select all

 token : "", 

 tokenSecret : "", 

 generateNonce : function () { 
     var nonce = ''; 
     for (var i = 0; i < 8; i++) { 
         var character = Math&#46;floor(Math&#46;random() * 61); 
         nonce += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'&#46;substring(character, character + 1); 
     } 
     return nonce; 
 }, 

 encodeSymbols : function (string){ 
     return encodeURIComponent(string)&#46;replace(&#47;[!'()]&#47;g, escape)&#46;replace(&#47;\*&#47;g, "%2A");   

},

Code: Select all

 calcHash : function (key, data) { 
     var hash = SHA1Lib&#46;core_hmac_sha1(key, data); 
     return SHA1Lib&#46;binb2b64(hash); 
 }, 

getHeader : function (apiUrl, params) {
if (typeof params == 'undefined') {
var params = {};
}

Code: Select all

     &#47;&#47;signParams to generate signature 
     var signParams = { 
         oauth_consumer_key: TwitterSearchSettings&#46;consumerKey,  
         oauth_version: '1&#46;0', 
         oauth_timestamp: Math&#46;round(new Date()&#46;getTime() &#47; 1000), 
         oauth_nonce: this&#46;generateNonce(), 
         oauth_signature_method: 'HMAC-SHA1' 
     }; 
     if (this&#46;token != ""){  
         signParams['oauth_token'] = this&#46;token;  
     } 

     &#47;&#47; oauthParams contains the parameters for authorization string 
     var oauthParams = {}; 
     for (var i in signParams) { 
         oauthParams[i] = signParams[i]; 
     } 

     &#47;&#47; add params to generate signature in signParams 
     for (var key in params) { 
         var value = params[key]; 
         signParams[key] = this&#46;encodeSymbols(value); 
     } 
     var keys = []; 
     for (var key in signParams) { 
         keys&#46;push(key); 
     }     
     keys&#46;sort(); 

     var signBaseString = ''; 
     for (var i=0; i<keys&#46;length; i++) { 
         var key = keys[i]; 
         var value = signParams[key]; 
         signBaseString += key + '=' + value + '&'; 
     } 
     signBaseString = signBaseString&#46;substring(0, signBaseString&#46;length - 1); 
     signBaseString = 'POST&' + this&#46;encodeSymbols(apiUrl) + '&' + this&#46;encodeSymbols(signBaseString); 

     var signingKey = TwitterSearchSettings&#46;consumerKeySecret + '&'; 
     if (this&#46;tokenSecret != ""){ 
        signingKey += this&#46;tokenSecret; 
     } 

     var signature = this&#46;calcHash(signingKey, signBaseString); 
     oauthParams['oauth_signature'] = signature; 

     &#47;&#47; creating authorization string 
     var authorization = 'OAuth '; 
     for (var key in oauthParams) { 
         var value = oauthParams[key]; 
         authorization += key + '="' + this&#46;encodeSymbols(value) + '", '; 
     } 
     return authorization&#46;substring(0, authorization&#46;length - 2); 
 } 

}/code

3) code&#47;&#47;correct replacement instead of standard from jQuery&#46;

jQuery&#46;param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
&#47;&#47; If value is a function, invoke it and return its value
value = jQuery&#46;isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s&#46;length ] = EncodeHelper&#46;encodeSymbols( key ) + "=" + EncodeHelper&#46;encodeSymbols( value );
};

&#47;&#47; Set traditional to true for jQuery <= 1&#46;3&#46;2 behavior&#46;
if ( traditional === undefined ) {
traditional = jQuery&#46;ajaxSettings && jQuery&#46;ajaxSettings&#46;traditional;
}

&#47;&#47; If an array was passed in, assume that it is an array of form elements&#46;
if ( jQuery&#46;isArray( a ) || ( a&#46;jquery && !jQuery&#46;isPlainObject( a ) ) ) {
&#47;&#47; Serialize the form elements
jQuery&#46;each( a, function() {
add( this&#46;name, this&#46;value );
});

} else {
&#47;&#47; If traditional, encode the "old" way (the way 1&#46;3&#46;2 or older
&#47;&#47; did it), otherwise encode params recursively&#46;
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}

&#47;&#47; Return the resulting serialization
return s&#46;join( "&" )&#46;replace( &#47;%20&#47;g, "+" );
};

function buildParams( prefix, obj, traditional, add ) {
var name;

if ( jQuery&#46;isArray( obj ) ) {
&#47;&#47; Serialize array item&#46;
jQuery&#46;each( obj, function( i, v ) {
if ( traditional || rbracket&#46;test( prefix ) ) {
&#47;&#47; Treat each array item as a scalar&#46;
add( prefix, v );

Code: Select all

} else { 
 &#47;&#47; If array item is non-scalar (array or object), encode its 
 &#47;&#47; numeric index to resolve deserialization ambiguity issues&#46; 
 &#47;&#47; Note that rack (as of 1&#46;0&#46;0) can't currently deserialize 
 &#47;&#47; nested arrays properly, and attempting to do so may cause 
 &#47;&#47; a server error&#46; Possible fixes are to modify rack's 
 &#47;&#47; deserialization algorithm or to provide an option or flag 
 &#47;&#47; to force array serialization to be shallow&#46; 
 buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); 
} 

});

} else if ( !traditional && jQuery&#46;type( obj ) === "object" ) {
&#47;&#47; Serialize object item&#46;
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}

} else {
&#47;&#47; Serialize scalar item&#46;
add( prefix, obj );
}
}
/code

Sean Kelley
Posts: 0
Joined: Thu Oct 11, 2012 2:25 pm

twitter tutorial- javascript

After pasting these into three separate JS files, I still get syntax error on console log at line 94 of first file:
Uncaught SyntaxError: Invalid regular expression: missing /
files/views/assets/js/TwitterSearchJS.js:94
which is the line:
this.handleError(reply.match(/(.*)<TwitSearchGlobal = {

Alena Prykhodko
Posts: 0
Joined: Tue Apr 09, 2013 7:36 am

twitter tutorial- javascript

Seems that braces are not closed. We'll check the code and update.

Return to “Issues”