/**
*
*/
package com.gmail.charleszq.picorner.task.flickr;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.gmail.charleszq.picorner.PicornerApplication;
import com.gmail.charleszq.picorner.R;
import com.gmail.charleszq.picorner.utils.FlickrHelper;
import com.gmail.charleszq.picorner.utils.IConstants;
import com.googlecode.flickrjandroid.Flickr;
import com.googlecode.flickrjandroid.auth.Permission;
import com.googlecode.flickrjandroid.oauth.OAuthToken;
/**
* Represents the task to start the oauth process.
*
* @author charles
*
*/
public class FlickrOAuthTask extends AsyncTask<Void, Integer, String> {
private final String TAG = FlickrOAuthTask.class.getSimpleName();
private static final Uri OAUTH_CALLBACK_URI = Uri
.parse(IConstants.ID_SCHEME + "://oauth"); //$NON-NLS-1$
/**
* The context.
*/
private Context mContext;
/**
* The progress dialog before going to the browser.
*/
private ProgressDialog mProgressDialog;
/**
* Constructor.
*
* @param context
*/
public FlickrOAuthTask(Context context) {
super();
this.mContext = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext,
"", mContext.getString(R.string.auth_gen_req_token)); //$NON-NLS-1$
mProgressDialog.setCanceledOnTouchOutside(true);
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dlg) {
FlickrOAuthTask.this.cancel(true);
}
});
}
/*
* (non-Javadoc)
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected String doInBackground(Void... params) {
try {
Flickr f = FlickrHelper.getInstance().getFlickr();
OAuthToken oauthToken = f.getOAuthInterface().getRequestToken(
OAUTH_CALLBACK_URI.toString());
saveTokenSecrent(oauthToken.getOauthTokenSecret());
URL oauthUrl = f.getOAuthInterface().buildAuthenticationUrl(
Permission.WRITE, oauthToken);
return oauthUrl.toString();
} catch (Exception e) {
Log.e(TAG, "Error to oauth", e); //$NON-NLS-1$
return "error:" + e.getMessage(); //$NON-NLS-1$
}
}
/**
* Saves the oauth token secrent.
*
* @param tokenSecret
*/
private void saveTokenSecrent(String tokenSecret) {
Activity act = (Activity) mContext;
PicornerApplication app = (PicornerApplication) act.getApplication();
app.saveFlickrTokenSecret(tokenSecret);
}
@Override
protected void onPostExecute(String result) {
if (mProgressDialog != null) {
try {
mProgressDialog.cancel();
} catch (Exception e) {
}
}
if (result != null && !result.startsWith("error")) { //$NON-NLS-1$
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri
.parse(result)));
} else {
Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
}
}
}