OSDN Git Service

OAuth
authorYuji Konishi <yuji.k64613@gmail.com>
Fri, 17 Aug 2012 08:44:34 +0000 (17:44 +0900)
committerYuji Konishi <yuji.k64613@gmail.com>
Fri, 17 Aug 2012 08:44:34 +0000 (17:44 +0900)
source/workspace/EverFolder/AndroidManifest.xml
source/workspace/EverFolder/gen/com/yuji/ef/R.java
source/workspace/EverFolder/res/layout/oauth.xml [new file with mode: 0644]
source/workspace/EverFolder/res/values/strings.xml
source/workspace/EverFolder/src/com/yuji/ef/OAuthActivity.java [new file with mode: 0644]
source/workspace/EverFolder/src/com/yuji/ef/SettingActivity.java
source/workspace/EverFolder/src/com/yuji/ef/task/NoteUpdateTask.java
source/workspace/EverFolder/src/com/yuji/ef/utility/EvernoteUtil.java

index 32f22eb..736ce14 100644 (file)
         android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" >
         <activity
             android:name=".EverFolderActivity"
-            android:label="@string/app_name" android:launchMode="singleTop">
+            android:label="@string/app_name"
+            android:launchMode="singleTop" >
             <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
 
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
-        <activity android:name=".SettingActivity" android:launchMode="singleTop">
+        <activity
+            android:name=".SettingActivity"
+            android:launchMode="singleTop" >
         </activity>
-
+        <activity
+            android:name=".OAuthActivity"
+            android:launchMode="singleTop" >
+        </activity>
+        <activity
+          android:name="com.evernote.client.oauth.android.EvernoteOAuthActivity"
+          android:launchMode="singleTask"
+          android:configChanges="orientation|keyboard">
+          <intent-filter>
+            <!-- Change this to be en- followed by your consumer key -->
+            <data android:scheme="en-yuji-k64613" />
+            <action android:name="android.intent.action.VIEW" />                
+            <category android:name="android.intent.category.BROWSABLE"/>
+            <category android:name="android.intent.category.DEFAULT" /> 
+          </intent-filter>
+        </activity>
+        
         <service
             android:name=".service.NoteUpdatorService"
             android:enabled="true" />
index 293b165..72234e6 100644 (file)
@@ -37,18 +37,20 @@ public final class R {
         public static final int mainMsgEditText=0x7f070003;
         public static final int mainMsgLayout=0x7f070001;
         public static final int mainMsgOkButton=0x7f070005;
+        public static final int oauthCloseButton=0x7f07000c;
         public static final int rightButton=0x7f07000b;
         public static final int scrollView=0x7f070007;
-        public static final int settingCloseButton=0x7f070011;
-        public static final int settingConfirmMsg=0x7f07000d;
-        public static final int settingLoginButton=0x7f07000e;
-        public static final int settingMsgLayout=0x7f07000c;
-        public static final int settingUpdateButton=0x7f07000f;
-        public static final int settingUpdateSpinner=0x7f070010;
+        public static final int settingCloseButton=0x7f070012;
+        public static final int settingConfirmMsg=0x7f07000e;
+        public static final int settingLoginButton=0x7f07000f;
+        public static final int settingMsgLayout=0x7f07000d;
+        public static final int settingUpdateButton=0x7f070010;
+        public static final int settingUpdateSpinner=0x7f070011;
     }
     public static final class layout {
         public static final int main=0x7f030000;
-        public static final int setting=0x7f030001;
+        public static final int oauth=0x7f030001;
+        public static final int setting=0x7f030002;
     }
     public static final class string {
         public static final int app_name=0x7f050000;
@@ -65,12 +67,13 @@ public final class R {
         public static final int noButton=0x7f050002;
         public static final int settingConfirmMsg=0x7f05000e;
         public static final int settingConfirmTitle=0x7f05000d;
-        public static final int settingLoginButton=0x7f050011;
-        public static final int settingLoginTitle=0x7f050010;
-        public static final int settingUpdateButton=0x7f050013;
+        public static final int settingLoginButton=0x7f050012;
+        public static final int settingLoginMsg=0x7f050010;
+        public static final int settingLoginTitle=0x7f050011;
+        public static final int settingUpdateButton=0x7f050014;
         public static final int settingUpdateMsg=0x7f05000f;
-        public static final int settingUpdateTimeTitle=0x7f050014;
-        public static final int settingUpdateTitle=0x7f050012;
+        public static final int settingUpdateTimeTitle=0x7f050015;
+        public static final int settingUpdateTitle=0x7f050013;
         public static final int yesButton=0x7f050001;
     }
 }
diff --git a/source/workspace/EverFolder/res/layout/oauth.xml b/source/workspace/EverFolder/res/layout/oauth.xml
new file mode 100644 (file)
index 0000000..fecf0cd
--- /dev/null
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="fill_parent"
+    android:layout_height="fill_parent"
+    android:orientation="vertical" >
+
+    <LinearLayout
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content" >
+
+        <Button
+            android:id="@+id/oauthCloseButton"
+            android:layout_width="fill_parent"
+            android:layout_height="wrap_content"
+            android:layout_weight="1"
+            android:text="@+string/closeButton" />
+    </LinearLayout>
+
+</LinearLayout>
\ No newline at end of file
index 28e20de..1c192c4 100644 (file)
@@ -33,6 +33,7 @@
     <string name="settingConfirmTitle">メッセージ</string>
     <string name="settingConfirmMsg">・・・</string>
     <string name="settingUpdateMsg">データ更新中</string>
+    <string name="settingLoginMsg">ログインをして下さい</string>
     <string name="settingLoginTitle">ログイン</string>
     <string name="settingLoginButton">ログインする</string>
     <string name="settingUpdateTitle">更新</string>
diff --git a/source/workspace/EverFolder/src/com/yuji/ef/OAuthActivity.java b/source/workspace/EverFolder/src/com/yuji/ef/OAuthActivity.java
new file mode 100644 (file)
index 0000000..80f0710
--- /dev/null
@@ -0,0 +1,217 @@
+package com.yuji.ef;
+//package com.evernote.android.sample;
+
+import java.io.File;
+
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.Environment;
+import android.view.View;
+import android.widget.Button;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.evernote.client.conn.ApplicationInfo;
+import com.evernote.client.oauth.android.AuthenticationResult;
+import com.evernote.client.oauth.android.EvernoteSession;
+import com.yuji.ef.utility.BaseActivity;
+import com.yuji.ef.utility.EvernoteUtil;
+
+/**
+ * This simple Android app demonstrates how to integrate with the Evernote Cloud
+ * API (aka EDAM) to create a note.
+ * 
+ * In this sample, the user authorizes access to their account using OAuth and
+ * chooses an image from the device's image gallery. The image is then saved
+ * directly to Evernote using the Cloud API.
+ */
+public class OAuthActivity extends BaseActivity {
+
+       /***************************************************************************
+        * You MUST change the following values to run this sample application. *
+        ***************************************************************************/
+
+       // Your Evernote API key. See http://dev.evernote.com/documentation/cloud/
+       // Please obfuscate your code to help keep these values secret.
+       private static final String CONSUMER_KEY = "yuji-k64613";
+       private static final String CONSUMER_SECRET = "98b2cbf35f747d2d";
+
+       /***************************************************************************
+        * Change these values as needed to use this code in your own application. *
+        ***************************************************************************/
+
+       // Name of this application, for logging
+       private static final String TAG = "HelloEDAM";
+
+       // A directory on disk where your application stores temporary data
+       private static final String APP_DATA_PATH = "/Android/data/com.yuji.ef/temp/";
+
+       // Change to "www.evernote.com" to use the Evernote production service
+       // instead of the sandbox
+       // private static final String EVERNOTE_HOST = "sandbox.evernote.com";
+       private static final String EVERNOTE_HOST = "www.evernote.com";
+
+       private static final String APP_NAME = "Evernote Android Sample";
+       private static final String APP_VERSION = "1.0";
+
+       /***************************************************************************
+        * The following values are simply part of the demo application. *
+        ***************************************************************************/
+
+       // Activity result request codes
+       private static final int SELECT_IMAGE = 1;
+
+       // The ENML preamble to every Evernote note.
+       // Note content goes between <en-note> and </en-note>
+       private static final String NOTE_PREFIX = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+                       + "<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">"
+                       + "<en-note>";
+
+       // The ENML postamble to every Evernote note
+       private static final String NOTE_SUFFIX = "</en-note>";
+
+       // Used to interact with the Evernote web service
+       private EvernoteSession session;
+
+       // UI elements that we update
+       private Button btnAuth;
+       private Button btnSave;
+       private Button btnSelect;
+       private TextView msgArea;
+
+       // The path to and MIME type of the currently selected image from the
+       // gallery
+       private String filePath;
+       private String mimeType;
+       private String fileName;
+
+       private boolean isInit = true;
+       
+       /** Called when the activity is first created. */
+       @Override
+       public void onCreate(Bundle savedInstanceState) {
+               super.onCreate(savedInstanceState);
+               setContentView(R.layout.oauth);
+
+//             msgArea = (TextView) findViewById(R.id.message);
+//             btnAuth = (Button) findViewById(R.id.auth_button);
+//             btnSelect = (Button) findViewById(R.id.select_button);
+//             btnSave = (Button) findViewById(R.id.save_button);
+
+               setupSession();
+       }
+
+       @Override
+       public void onResume() {
+               super.onResume();
+
+               // Complete the Evernote authentication process if necessary
+               // TODO
+               //if (!session.completeAuthentication()) {
+               if (!isInit && !session.completeAuthentication()) {
+                       // We only want to do this when we're resuming after
+                       // authentication...
+                       Toast.makeText(this, "Evernote login failed", Toast.LENGTH_LONG)
+                                       .show();
+               }
+
+               updateUi();
+               
+               // ADD
+               if (isInit){
+                       isInit = false;
+               }
+               else {
+                       EvernoteUtil util = EvernoteUtil.getInstance();
+                       util.setSession(session);
+                       finish();
+               }
+       }
+
+       /**
+        * Setup the EvernoteSession used to access the Evernote API.
+        */
+       private void setupSession() {
+               ApplicationInfo info = new ApplicationInfo(CONSUMER_KEY,
+                               CONSUMER_SECRET, EVERNOTE_HOST, APP_NAME, APP_VERSION);
+
+               String authToken = null;
+               String noteStoreUrl = null;
+               String webApiUrlPrefix = null;
+               int userId = 0;
+               // boolean hasCachedEvernoteCredentials = true;
+               boolean hasCachedEvernoteCredentials = false;
+
+               // TODO Retreived the cached Evernote AuthenticationResult if it exists
+               if (hasCachedEvernoteCredentials) {
+                       AuthenticationResult result = new AuthenticationResult(authToken,
+                                       noteStoreUrl, webApiUrlPrefix, userId);
+                       session = new EvernoteSession(info, result, getTempDir());
+               } else {
+                       session = new EvernoteSession(info, getTempDir());
+               }
+
+               updateUi();
+               
+               // ADD
+               try {
+                       startAuth(null);
+               }
+               catch (Throwable t){
+                       t.printStackTrace();
+               }
+       }
+
+       /**
+        * Update the UI based on Evernote authentication state.
+        */
+       private void updateUi() {
+               if (session.isLoggedIn()) {
+//                     btnAuth.setText(R.string.label_log_out);
+//                     btnSave.setEnabled(true);
+//                     btnSelect.setEnabled(true);
+               } else {
+//                     btnAuth.setText(R.string.label_log_in);
+//                     btnSave.setEnabled(false);
+//                     btnSelect.setEnabled(false);
+               }
+       }
+
+       /**
+        * Called when the user taps the "Select Image" button.
+        * 
+        * Sends the user to the image gallery to choose an image to share.
+        */
+       public void startAuth(View view) {
+               if (session.isLoggedIn()) {
+                       session.logOut();
+               } else {
+                       session.authenticate(this);
+               }
+               updateUi();
+       }
+
+       /**
+        * Get a temporary directory that can be used by this application to store
+        * potentially large files sent to and retrieved from the Evernote API.
+        */
+       private File getTempDir() {
+               return new File(Environment.getExternalStorageDirectory(),
+                               APP_DATA_PATH);
+       }
+
+       /**
+        * Called when the control returns from an activity that we launched.
+        */
+       @Override
+       public void onActivityResult(int requestCode, int resultCode, Intent data) {
+               super.onActivityResult(requestCode, resultCode, data);
+               if (requestCode == SELECT_IMAGE) {
+                       // Callback from our 'startSelectImage' action
+                       if (resultCode == Activity.RESULT_OK) {
+//                             endSelectImage(data);
+                       }
+               }
+       }
+}
index 8900568..bd6b6cc 100644 (file)
@@ -27,6 +27,7 @@ import com.yuji.ef.task.NoteUpdateTask;
 import com.yuji.ef.utility.AsyncTaskCommand;
 import com.yuji.ef.utility.BaseActivity;
 import com.yuji.ef.utility.Debug;
+import com.yuji.ef.utility.EvernoteUtil;
 
 public class SettingActivity extends BaseActivity {
        private EditPrefUtil pref = new EditPrefUtil(this);
@@ -41,6 +42,9 @@ public class SettingActivity extends BaseActivity {
        private boolean isRegister = false;
        private boolean isBind = false;
 
+       private boolean lock = false;
+       private boolean isInit = true;
+       
        private class NoteUpdatorReceiver extends BroadcastReceiver {
 
                @Override
@@ -112,13 +116,17 @@ public class SettingActivity extends BaseActivity {
                noteOrderAdapter
                                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                updateSpinner.setAdapter(noteOrderAdapter);
-               setStatus();
        }
 
        @Override
        protected void onStart() {
-               super.onStart();
-
+               super.onStart();                
+       }
+       
+       @Override
+       protected void onResume() {
+               super.onResume();
+               
                int updateTime = pref.getInt(Constant.PREF_UPDATE_TIME, 0);
 
                String[] values = getResources().getStringArray(
@@ -129,6 +137,11 @@ public class SettingActivity extends BaseActivity {
                                break;
                        }
                }
+               
+               if (isInit){
+                       setStatus();
+                       isInit = false;
+               }
        }
 
        @Override
@@ -164,6 +177,11 @@ public class SettingActivity extends BaseActivity {
                super.onPause();
        }
 
+       @Override
+       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+               isInit = true;
+       }
+       
        private void stopService() {
                NoteUpdatorService.stopService(this);
        }
@@ -188,12 +206,13 @@ public class SettingActivity extends BaseActivity {
        }
 
        private void loginButtonOnClick(){
-               // TODO
+               Intent intent = new Intent(this, (Class<?>) OAuthActivity.class);
+               startActivityForResult(intent, 0);
        }
        
        private void updateButtonOnClick() {
                LockDao lockDao = (LockDao) LockDao.getInstance();
-               boolean lock = lockDao.lock(this, Constant.LOCK_UPDATE_NOTE);
+               lock = lockDao.lock(this, Constant.LOCK_UPDATE_NOTE);
 
                if (!lock) {
                        setStatus();
@@ -216,7 +235,8 @@ public class SettingActivity extends BaseActivity {
        public void done(int errorCode) {
                LockDao lockDao = (LockDao) LockDao.getInstance();
                lockDao.unlock(this, Constant.LOCK_UPDATE_NOTE);
-
+               lock = false;
+               
                setStatus();
        }
 
@@ -230,15 +250,32 @@ public class SettingActivity extends BaseActivity {
        }
 
        private void setStatus() {
-               LockDao lockDao = (LockDao) LockDao.getInstance();
-               boolean lock = lockDao.isLock(this, Constant.LOCK_UPDATE_NOTE);
-
                if (lock) {
                        msgLayout.setVisibility(View.VISIBLE);
                        confirmMsg.setText(getString(R.string.settingUpdateMsg));
+                       
+                       loginButton.setEnabled(false);
+                       updateButton.setEnabled(false);
+                       updateSpinner.setEnabled(false);
+                       
                        return;
                }
 
+               EvernoteUtil util = EvernoteUtil.getInstance();
+               if (!util.isLoggedIn()) {
+                       msgLayout.setVisibility(View.VISIBLE);
+                       confirmMsg.setText(getString(R.string.settingLoginMsg));
+                       
+                       loginButton.setEnabled(true);
+                       updateButton.setEnabled(false);
+                       updateSpinner.setEnabled(false);
+                       
+                       return;
+               }
+               
+               loginButton.setEnabled(true);
+               updateButton.setEnabled(true);
+               updateSpinner.setEnabled(true);
                msgLayout.setVisibility(View.GONE);
        }
 }
index a19d254..524756f 100644 (file)
@@ -23,6 +23,7 @@ public class NoteUpdateTask implements AsyncTaskIF {
                }
                catch (Exception e){
                        // TODO
+                       e.printStackTrace();
                }
        }
 
index 2098a5a..3d7c0cc 100644 (file)
@@ -9,6 +9,7 @@ import org.apache.thrift.protocol.TBinaryProtocol;
 import org.apache.thrift.transport.THttpClient;
 import org.apache.thrift.transport.TTransportException;
 
+import com.evernote.client.oauth.android.EvernoteSession;
 import com.evernote.edam.error.EDAMErrorCode;
 import com.evernote.edam.error.EDAMNotFoundException;
 import com.evernote.edam.error.EDAMSystemException;
@@ -28,6 +29,7 @@ public class EvernoteUtil {
        private static final int N = 50;
        private String username;
        private String password;
+       private EvernoteSession session;
 
        public enum Error {
                NONE, CONNECT, INVALID_AUTH, NOT_FOUND, OTHER
@@ -284,7 +286,24 @@ public class EvernoteUtil {
                return n;
        }
 
+       public boolean isLoggedIn(){
+               return session != null;
+       }
+       
        private String getAuthenticationToken() {
+               if (authenticationToken == null) {
+                       authenticationToken = session.getAuthToken();           
+                       try {
+                               noteStore = session.createNoteStore();
+                       } catch (TTransportException e) {
+                               // TODO
+                               authenticationToken = null;
+                       }
+               }
+               return authenticationToken;
+       }
+       
+       private String getAuthenticationTokenBak() {
                try {
                        if (authenticationToken == null) {
                                // String userStoreUrl =
@@ -347,6 +366,11 @@ public class EvernoteUtil {
                return errorCode;
        }
 
+       public void setSession(EvernoteSession session) {
+               this.session = session;
+       }
+
+       
 //     public String getErrorMessage(Context context, Error code) {
 //             if (code.equals(Error.NONE)) {
 //                     return "";