Skip to content

Instantly share code, notes, and snippets.

@Rogichi
Last active December 19, 2015 05:29
Show Gist options
  • Select an option

  • Save Rogichi/5905010 to your computer and use it in GitHub Desktop.

Select an option

Save Rogichi/5905010 to your computer and use it in GitHub Desktop.
Tweet Example (Using VIEZEL Codebird for Appcelerator Titanium. Twitter API 1.1 https://gist.github.com/viezel/5781083 ):
// How Publish a Tweet (Titanium)
// Full Codebird API is here: https://github.com/mynetx/codebird-js
// Codebird for Appcelerator Titanium. Using the Twitter API 1.1: https://gist.github.com/viezel/5781083
//THANKS VIEZEL
var win = Ti.UI.createWindow(); // Main Window
var twitter = Ti.UI.createButton({
title:'Set Tweet'
});
var accessToken=null;
var accessTokenSecret=null;
///////////LOAD ACCESS TOKEN
loadAccessToken = function(pService) {
Ti.API.info('Loading access token for service [' + pService + '].');
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, pService + '.config');
if (file.exists() == false){
return;
}
var contents = file.read();
if (contents == null){
return;
}
var config;
try {
config = JSON.parse(contents.text);
} catch(ex) {
return;
}
if (!config) {
return;
}
if (config.accessToken){
accessToken = config.accessToken;
}
if (config.accessTokenSecret){
accessTokenSecret = config.accessTokenSecret;
}
Ti.API.info('Loading access token: done [accessToken:' + accessToken + '][accessTokenSecret:' + accessTokenSecret + '].');
};
///////////SAVE ACCESS TOKEN
saveAccessToken = function(pService) {
Ti.API.info('Saving access token [' + pService + '].');
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, pService + '.config');
if (file == null){
file = Ti.Filesystem.createFile(Ti.Filesystem.applicationDataDirectory, pService + '.config');
}
file.write(JSON.stringify({
accessToken: accessToken,
accessTokenSecret: accessTokenSecret
}));
Ti.API.info('Saving access token: done.');
};
///////////CLEAR ACCESS TOKEN
clearAccessToken = function(pService) {
var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, pService + '.config');
if (file == null){
file = Ti.Filesystem.createFile(Ti.Filesystem.applicationDataDirectory, pService + '.config');
}
file.write(JSON.stringify({
accessToken: null,
accessTokenSecret: null
}));
accessToken = null;
accessTokenSecret = null;
};
var Codebird = require("codebird");
var cb = new Codebird();
cb.setConsumerKey('ConsumerKey', 'Consumer Secret');
///////////SET TWEET FUNCTION
function setTweet(){
cb.__call(
"statuses_update",
{"status": "Whohoo, I just tweeted!"},
function (reply) {
Ti.API.info("Respuesta al publicar: ");// ...
//Ti.API.info(reply);// ...
///////////INSPECT OBJECT
function inspeccionar(obj){
var msg = '';
for (var property in obj){
if (typeof obj[property] == 'function')
{
var inicio = obj[property].toString().indexOf('function');
var fin = obj[property].toString().indexOf(')')+1;
var propertyValue=obj[property].toString().substring(inicio,fin);
msg +=(typeof obj[property])+' '+property+' : '+propertyValue+' ;\n';
}
else if (typeof obj[property] == 'unknown')
{
msg += 'unknown '+property+' : unknown ;\n';
}
else
{
msg +=(typeof obj[property])+' '+property+' : '+obj[property]+' ;\n';
}
}
return msg;
}
//Ti.API.info(inspeccionar(reply));
//Ti.API.info(inspeccionar(reply.errors[0]));
//Ti.API.info(reply.httpstatus);
if(reply.httpstatus == 200)
alert("Tweet exitoso!!!");
else
alert(reply.errors[0].message);
}
);
}
twitter.addEventListener('click',function(e){
/////////// SET TWEET ///////////
//clearAccessToken('twitter');
loadAccessToken('twitter');
if(accessTokenSecret!=null && accessToken!=null)
{
cb.setToken(accessToken, accessTokenSecret);
setTweet();
}
else
{
cb.__call(
"oauth_requestToken",
{oauth_callback: "oob"},
function (reply) {
// stores it
cb.setToken(reply.oauth_token, reply.oauth_token_secret);
// gets the authorize screen URL
cb.__call(
"oauth_authorize",
{},
function (auth_url) {
//window.codebird_auth = window.open(auth_url);
Ti.API.info(auth_url);// ...
var window = Titanium.UI.createWebView({
height:"100%",
width:"100%",
url:auth_url
});
closeLabel = Ti.UI.createLabel({
textAlign: 'right',
font: {
fontWeight: 'bold',
fontSize: '12pt'
},
text: '(X)',
top: 0,
right: 0,
height: 14
});
window.add(closeLabel);
closeLabel.addEventListener('click', function(e){ win.remove(window)});
var destroyAuthorizeUI = function() {
Ti.API.info('destroyAuthorizeUI');
// remove the UI
try {
window.removeEventListener('load', authorizeUICallback);
win.remove(window);
window = null;
}
catch(ex) {
Ti.API.info('Cannot destroy the authorize UI. Ignoring.');
}
};
var authorizeUICallback = function(e) {
Ti.API.info('authorizeUILoaded');
//alert('authorizeUILoaded');
//var val = window.evalJS('document.getElementById("PINFIELD").value');
var val = window.evalJS('window.document.querySelector(\'kbd[aria-labelledby="code-desc"] > code\').innerHTML');
Ti.API.info(val);
//alert(window.html);
if (val) {
destroyAuthorizeUI();
cb.__call(
"oauth_accessToken",
{oauth_verifier: val},
function (reply) {
// store the authenticated token, which may be different from the request token (!)
cb.setToken(reply.oauth_token, reply.oauth_token_secret);
Ti.API.info(reply);
setTweet();
accessToken = reply.oauth_token;
accessTokenSecret=reply.oauth_token_secret;
saveAccessToken('twitter');
}
);
}
};
window.addEventListener('load', authorizeUICallback);
win.add(window);
}
);
}
);
}
});
win.add(twitter);
win.open();
@iantearle
Copy link
Copy Markdown

Hi, the tokens weren't saving, the file was being written with null values. I'm guess because you dont actually send the tokens to the saveAccessToken function?

I added the following:

saveAccessToken('twitter', reply.oauth_token, reply.oauth_token_secret);

Let me know if you did something different and this is just an older version?

@Rogichi
Copy link
Copy Markdown
Author

Rogichi commented Jul 3, 2013

Sorry, my fault!!!! I was so exited because of the tweet and I forgot save the tokens into the global vars.

Wrong:

setTweet();
reply.oauth_token=null;
reply.oauth_token_Secret=null;
saveAccessToken('twitter')   

Right:

setTweet();
accessToken = reply.oauth_token;
accessTokenSecret=reply.oauth_token_secret;
saveAccessToken('twitter');

Sorry for my english.

@iantearle
Copy link
Copy Markdown

Not a problem at all. Great work on getting it done. Its fantastic!

@fit4him
Copy link
Copy Markdown

fit4him commented Jul 10, 2013

Would love to get codebird implemented. I get the following error when running code below: Any ideas?

Can't find HTTP method to use for "statuses/user/timeline".
[WARN] : 2013-07-10 11:18:53.085 LFCMobileAlloy[95028:21407] 95028: CFNetwork internal error (0xc01a:/SourceCache/CFNetwork_Sim/CFNetwork-609.1.4/HTTP/HTTPRequestParserClient.h:28)
[WARN] : 2013-07-10 11:18:53.087 LFCMobileAlloy[95028:21407] [WARN] Unable to securely connect to api.twitter.com with the latest TLS. Trying again with TLS1.0. It is highly suggested that the server be updated to the latest TLS support.
[WARN] : 2013-07-10 11:18:53.173 LFCMobileAlloy[95028:21407] 95028: CFNetwork internal error (0xc01a:/SourceCache/CFNetwork_Sim/CFNetwork-609.1.4/HTTP/HTTPRequestParserClient.h:28)

cb.__call(
'statuses/user_timeline',
"purplepastor",
function (tweets) {

for (var c=0;c<tweets.length;c++){

    var tweet = tweets[c].text;
    alert(c);
}
}

);

@Rogichi
Copy link
Copy Markdown
Author

Rogichi commented Jul 24, 2013

mmm no, do you want to get all tweets from the timeline?

@albinotonnina
Copy link
Copy Markdown

And instead I geto a strange type error when I user your app.js and codebird 2.4.3...
I'm quite sure that the resources are in the right place too.
and i'm on an alloy project but should work quite the same...

[ERROR] : Script Error {
[ERROR] : message = "'[object Object]' is not a constructor (evaluating 'new Codebird()')";
[ERROR] : name = TypeError;
[ERROR] : sourceId = 349446528;
[ERROR] : sourceURL =
[ERROR] : }

@albinotonnina
Copy link
Copy Markdown

If I use this version (2.4.0 dev): https://gist.github.com/viezel/5781083#file-codebird-js
it works

@edouardouvrard
Copy link
Copy Markdown

My reply.oauth_token and reply.oauth_token_Secret are NULL , do you have an idea why ?

@roseanne123
Copy link
Copy Markdown

@Rogichi I pasted your code in exactly but pressing thee button set tweet did nothing. Is there something I'm missing?

@roseanne123
Copy link
Copy Markdown

@Rogichi Ok, I got a post working, thanks! It only works the first time though. I then have to close the app and re-open to post a second tweet. Also, is there any way when a user clicks the button 'set tweet' that I could open up a dialog and having a pre-defined message there, which the user can edit, press ok or press cancel?

@AppWerft
Copy link
Copy Markdown

Here I have coded a version which begins with app only authorization (bearer) and continues with 3-leg-auth. after tweeting: https://github.com/AppWerft/Nacht-des-Wissens/blob/master/Resources/model/twitter_adapter.js

@MukundSamant
Copy link
Copy Markdown

@roseanne123
I know its been 3 months,but just to clarify. It will work only the first time.Twitter does not allow posting the same string twice in a row.

@MukundSamant
Copy link
Copy Markdown

@Rogichi

Good job mate really helpful!!

@powysm
Copy link
Copy Markdown

powysm commented Jan 25, 2014

I get the following when i setup and run:

[INFO] : Loading access token for service [twitter].
[ERROR] : xhr2 object not defined, trying ActiveXObject.
[ERROR] : ActiveXObject object not defined, cancelling.

Clearly there is an issue with codebird finding either : xmlhttprequest, xhr2 or Microsoft.XMLHTTP.
I believe i have the project setup correctly with my consumer key and secret.
Titanium 3.2.0 SDK
I am a newbie to titanium so probably got some config or dependencies wrong. Grateful for any help.

@horovody
Copy link
Copy Markdown

@powysm
Hi!
I had the same issue with new codebird library. Looks like they added some xmlhttprequest code, that does't work on iPhone/iPad (i've tested only on these devices).
So I just took the codebird.js file with 2.4.0 version from this gist https://gist.github.com/viezel/5781083. Hope this helps.

@iekucukcay
Copy link
Copy Markdown

@Rogichi,
Thank you very much indeed! Pretty much straightforward and practical.

@powysm
Copy link
Copy Markdown

powysm commented Mar 16, 2014

Hi,
Does the line 232 - ..window.evalJS... i.e. the bit that scrapes the pin, work for anyone else in titanium?
I am having to manually add the pin into an input field.
Thanks

@AlokGupta007
Copy link
Copy Markdown

Thanks Rogichi ! It is helpful . It has simple auth process and post tweet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment