Merge branch 'develop' into refresh_folder_contents_when_browsed_into
authormasensio <masensio@solidgear.es>
Fri, 20 Sep 2013 08:19:44 +0000 (10:19 +0200)
committermasensio <masensio@solidgear.es>
Fri, 20 Sep 2013 08:19:44 +0000 (10:19 +0200)
Conflicts:
src/com/owncloud/android/operations/SynchronizeFolderOperation.java

44 files changed:
AndroidManifest.xml
oc_jb_workaround/AndroidManifest.xml
res/layout-land/account_setup.xml
res/layout/account_setup.xml
res/layout/sso_dialog.xml [new file with mode: 0644]
res/values-es/strings.xml
res/values-tr/strings.xml
res/values-zh-rCN/strings.xml
res/values-zh-rTW/strings.xml
res/values/branding.xml [deleted file]
res/values/oauth2_configuration.xml
res/values/setup.xml [new file with mode: 0644]
res/values/strings.xml
res/values/styles.xml
src/com/owncloud/android/authentication/AccountAuthenticator.java
src/com/owncloud/android/authentication/AccountAuthenticatorActivity.java [new file with mode: 0644]
src/com/owncloud/android/authentication/AccountUtils.java
src/com/owncloud/android/authentication/AuthenticatorActivity.java
src/com/owncloud/android/authentication/SsoWebViewClient.java [new file with mode: 0644]
src/com/owncloud/android/datamodel/FileDataStorageManager.java
src/com/owncloud/android/files/services/FileDownloader.java
src/com/owncloud/android/files/services/FileUploader.java
src/com/owncloud/android/network/OwnCloudClientUtils.java
src/com/owncloud/android/operations/ChunkedUploadFileOperation.java
src/com/owncloud/android/operations/CreateFolderOperation.java
src/com/owncloud/android/operations/DownloadFileOperation.java
src/com/owncloud/android/operations/ExistenceCheckOperation.java
src/com/owncloud/android/operations/OAuth2GetAccessToken.java
src/com/owncloud/android/operations/OwnCloudServerCheckOperation.java
src/com/owncloud/android/operations/RemoteOperation.java
src/com/owncloud/android/operations/RemoteOperationResult.java
src/com/owncloud/android/operations/RemoveFileOperation.java
src/com/owncloud/android/operations/RenameFileOperation.java
src/com/owncloud/android/operations/SynchronizeFileOperation.java
src/com/owncloud/android/operations/SynchronizeFolderOperation.java
src/com/owncloud/android/operations/UpdateOCVersionOperation.java
src/com/owncloud/android/operations/UploadFileOperation.java
src/com/owncloud/android/providers/FileContentProvider.java
src/com/owncloud/android/syncadapter/FileSyncAdapter.java
src/com/owncloud/android/ui/activity/AccountSelectActivity.java
src/com/owncloud/android/ui/activity/FileActivity.java
src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java [new file with mode: 0644]
src/com/owncloud/android/ui/dialog/SsoWebView.java [new file with mode: 0644]
src/eu/alefzero/webdav/WebdavClient.java

index 452143c..9145aba 100644 (file)
@@ -18,8 +18,8 @@
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
  -->
 <manifest package="com.owncloud.android"
-    android:versionCode="104004"
-    android:versionName="1.4.4" xmlns:android="http://schemas.android.com/apk/res/android">
+    android:versionCode="104005"
+    android:versionName="1.4.5" xmlns:android="http://schemas.android.com/apk/res/android">
 
     <uses-permission android:name="android.permission.GET_ACCOUNTS" />
     <uses-permission android:name="android.permission.USE_CREDENTIALS" />
index f3b4181..cdb77bc 100644 (file)
@@ -1,8 +1,8 @@
 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.owncloud.android.workaround.accounts"
-    android:versionCode="0100006"
-    android:versionName="1.0.6" >
+    android:versionCode="0100007"
+    android:versionName="1.0.7" >
 
     <uses-sdk
         android:minSdkVersion="16"
index 150893a..fed4dce 100644 (file)
@@ -43,6 +43,7 @@
                    android:layout_width="0dp"\r
                    android:layout_height="match_parent"\r
                    android:layout_weight="1"\r
+                   android:id="@+id/scroll"\r
                    android:fillViewport="true"\r
                    android:orientation="vertical" >\r
                                                \r
@@ -50,7 +51,6 @@
                            android:id="@+id/LinearLayout1"\r
                            android:layout_width="match_parent"\r
                            android:layout_height="wrap_content"\r
-                           android:focusable="true"\r
                            android:gravity="center"\r
                            android:orientation="vertical"\r
                            android:padding="8dp" >\r
                        android:onClick="onRefreshClick"\r
                                    android:text="@string/auth_check_server"\r
                                    android:visibility="gone" />\r
-               \r
+                               <TextView\r
+                                   android:id="@+id/auth_message"\r
+                                   android:layout_width="wrap_content"\r
+                                   android:layout_height="wrap_content"\r
+                                   android:layout_gravity="fill_horizontal"\r
+                                   android:text="@string/auth_expired_basic_auth_toast" \r
+                                   android:visibility="gone"\r
+                                   android:layout_marginBottom="10dp"/>\r
                            <FrameLayout \r
                                android:id="@+id/hostUrlFrame"\r
                                        android:layout_width="match_parent"\r
                                        android:onClick="onCheckClick"\r
                                        android:text="@string/oauth_check_onoff"\r
                                        android:textAppearance="?android:attr/textAppearanceSmall"\r
-                                       android:visibility="gone"\r
                                        />\r
                \r
                                <EditText\r
                                        android:singleLine="true"\r
                                        android:inputType="textUri"\r
                                        android:visibility="gone" >\r
-                                       <requestFocus />\r
                                </EditText>            \r
                                \r
                                <EditText\r
index 04da4be..52a8ed2 100644 (file)
     android:layout_height="match_parent"\r
     android:layout_gravity="center"\r
     android:fillViewport="true"\r
-    android:orientation="vertical" >\r
+    android:orientation="vertical" \r
+    android:id="@+id/scroll"\r
+    >\r
 \r
     <LinearLayout\r
         android:layout_width="match_parent"\r
         android:layout_height="wrap_content"\r
-        android:focusable="true"\r
         android:gravity="center"\r
         android:orientation="vertical"\r
         android:padding="8dp" >\r
             android:onClick="onRefreshClick"\r
             android:text="@string/auth_check_server"\r
             android:visibility="gone" />\r
+        \r
+        <TextView\r
+            android:id="@+id/auth_message"\r
+            android:layout_width="wrap_content"\r
+            android:layout_height="wrap_content"\r
+            android:layout_gravity="fill_horizontal"\r
+            android:text="@string/auth_expired_basic_auth_toast"\r
+            android:visibility="gone"\r
+            android:layout_marginBottom="10dp" />\r
 \r
            <FrameLayout \r
                android:id="@+id/hostUrlFrame"\r
             android:onClick="onCheckClick"\r
             android:text="@string/oauth_check_onoff"\r
             android:textAppearance="?android:attr/textAppearanceSmall"\r
-            android:visibility="gone" />\r
+            />\r
 \r
         <EditText\r
             android:id="@+id/oAuthEntryPoint_1"\r
             android:layout_width="match_parent"\r
             android:layout_height="wrap_content"\r
             android:ems="10"\r
-            android:inputType="textUri"\r
-            android:singleLine="true"\r
+                       android:enabled="false"\r
             android:text="@string/oauth2_url_endpoint_auth"\r
+            android:singleLine="true"\r
+            android:inputType="textUri"\r
             android:visibility="gone" >\r
         </EditText>\r
 \r
             android:layout_width="match_parent"\r
             android:layout_height="wrap_content"\r
             android:ems="10"\r
-            android:inputType="textUri"\r
-            android:singleLine="true"\r
+                       android:enabled="false"\r
             android:text="@string/oauth2_url_endpoint_access"\r
+            android:singleLine="true"\r
+            android:inputType="textUri"\r
             android:visibility="gone" />\r
 \r
         <EditText\r
             android:layout_height="wrap_content"\r
             android:ems="10"\r
             android:hint="@string/auth_username"\r
-            android:inputType="textNoSuggestions" />\r
+            android:inputType="textNoSuggestions" \r
+                       />\r
 \r
                <EditText\r
                    android:id="@+id/account_password"\r
                    android:drawablePadding="5dp"\r
                    android:ems="10"\r
                    android:hint="@string/auth_password"\r
-                   android:inputType="textPassword" />\r
+                   android:inputType="textPassword" \r
+            />\r
         \r
         <TextView\r
             android:id="@+id/auth_status_text"\r
diff --git a/res/layout/sso_dialog.xml b/res/layout/sso_dialog.xml
new file mode 100644 (file)
index 0000000..788a0e2
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ownCloud Android client application
+
+  Copyright (C) 2012-2013 ownCloud Inc.
+
+  This program is free software: you can redistribute it and/or modify
+  it under the terms of the GNU General Public License version 2,
+  as published by the Free Software Foundation.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+-->
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    >
+    
+    <com.owncloud.android.ui.dialog.SsoWebView
+       android:layout_width="wrap_content"
+       android:layout_height="wrap_content"
+        android:id="@+id/sso_webview"
+        android:focusable="true"
+        android:focusableInTouchMode="true"
+        android:clickable="true"
+        />
+
+</RelativeLayout>
index 065e95b..8e6ad5e 100644 (file)
   <string name="auth_not_found">Ruta errónea</string>
   <string name="auth_internal">Error interno en el servidor, código %1$d</string>
   <string name="auth_wtf_reenter_URL">Estado inesperado; por favor, introduzca la URL del servidor de nuevo</string>
-  <string name="auth_expired_oauth_token_toast">Su autorización ha expirado.\nPor favor, autorice de nuevo</string>
+  <string name="auth_expired_oauth_token_toast">Su autorización ha expirado. Por favor, autorice de nuevo</string>
   <string name="auth_expired_basic_auth_toast">Por favor, introduzca la contraseña actual.</string>
   <string name="crashlog_message">La aplicación finalizó inesperadamente. ¿Desea enviar un reporte de error?</string>
   <string name="crashlog_send_report">Enviar reporte</string>
index 9a6af45..2bcd263 100644 (file)
@@ -19,6 +19,7 @@
   <string name="actionbar_mkdir">Klasör yarat</string>
   <string name="actionbar_search">Arama</string>
   <string name="actionbar_settings">Ayarlar</string>
+  <string name="actionbar_see_details">Detaylar</string>
   <string name="prefs_category_general">Genel</string>
   <string name="prefs_add_session">Yeni oturum ekle</string>
   <string name="prefs_create_img_thumbnails">Küçük resim oluştur</string>
@@ -49,6 +50,7 @@
   <string name="setup_title">ownCloud\'nıza bağlanin</string>
   <string name="setup_btn_connect">Bağlan</string>
   <string name="uploader_btn_upload_text">Yükle</string>
+  <string name="uploader_top_message">Yükleme dizinini seçiniz:</string>
   <string name="uploader_wrn_no_account_title">Hesap bulunamadi</string>
   <string name="uploader_wrn_no_account_text">Cihazınızda ownCloud hesabı bulunmamaktadır. Lütfen öncelikle bir hesap ayarı giriniz.</string>
   <string name="uploader_wrn_no_account_setup_btn_text">Kurulum</string>
@@ -76,6 +78,7 @@
   <string name="common_save_exit">Kaydet %amp; Kapat</string>
   <string name="common_exit">Çıkış</string>
   <string name="common_error">Hata</string>
+  <string name="common_loading">Yükleniyor...</string>
   <string name="common_error_unknown">Bilinmeyen hata</string>
   <string name="about_title">Hakkında</string>
   <string name="change_password">Parola değiştir</string>
   <string name="downloader_download_succeeded_content">%1$s başarıyla indirildi</string>
   <string name="downloader_download_failed_ticker">İndirilme başarısız</string>
   <string name="downloader_download_failed_content">%1$s indirilmesi tamamlanamadı</string>
+  <string name="downloader_not_downloaded_yet">Henüz indirilemedi</string>
   <string name="common_choose_account">Hesap seçiniz</string>
   <string name="sync_string_contacts">Kontaklar</string>
   <string name="sync_fail_ticker">Eşitleme başarısız</string>
   <string name="pincode_wrong">Yanlış ownCloud App PIN</string>
   <string name="pincode_removed">ownCloud App PIN kaldırıldı</string>
   <string name="pincode_stored">ownCloud App PIN saklandı</string>
+  <string name="media_notif_ticker">%1$s müzik çalar</string>
+  <string name="media_state_playing">%1$s (oynatılıyor)</string>
+  <string name="media_state_loading">%1$s (yükleniyor)</string>
+  <string name="media_event_done">%1$s yeniden oynatım sonlandırıldı</string>
+  <string name="media_err_nothing_to_play">Herhangi bir medya öğesi bulunamadı</string>
+  <string name="media_err_not_in_owncloud">Dosya doğru bir hesapta değil</string>
+  <string name="media_err_unsupported">Codec desteklenmiyor</string>
+  <string name="media_err_io">Medya öğesi okunamadı</string>
+  <string name="media_err_malformed">Medya öğesi doğru bir şekilde kodlanmadı</string>
+  <string name="media_err_timeout">Oynatmak için fazla deneme yapıldı</string>
+  <string name="media_err_invalid_progressive_playback">Medya öğesi aktarılamadı</string>
   <string-array name="prefs_trackmydevice_intervall_keys">
     <item>15 Dakika</item>
     <item>30 Dakika</item>
index e2a42dc..702c63a 100644 (file)
   <string name="main_settings">设置</string>
   <string name="main_tit_accsetup">设置账号</string>
   <string name="main_wrn_accsetup">设备上无 ownCloud 账号,要使用此 App,需要先创建一个账号。</string>
+  <string name="about_version">版本:%1</string>
+  <string name="actionbar_sync">刷新帐户</string>
   <string name="actionbar_upload">上传</string>
   <string name="actionbar_upload_from_apps">来自其它app的内容</string>
   <string name="actionbar_upload_files">文件</string>
+  <string name="actionbar_open_with">打开</string>
   <string name="actionbar_mkdir">创建目录</string>
   <string name="actionbar_search">搜索</string>
   <string name="actionbar_settings">设置</string>
   <string name="prefs_pincode_summary">保护您的owncloud客户端</string>
   <string name="prefs_instant_upload">开启即时上传</string>
   <string name="prefs_instant_upload_summary">即时上传相机拍摄的照片</string>
+  <string name="prefs_log_title">开启日志</string>
+  <string name="prefs_log_title_history">日志历史</string>
+  <string name="prefs_log_delete_history_button">删除历史</string>
+  <string name="auth_check_server">检查服务器</string>
   <string name="auth_host_url">服务器地址</string>
   <string name="auth_username">用户名</string>
   <string name="auth_password">密码</string>
   <string name="sync_string_contacts">联系人</string>
   <string name="sync_fail_ticker">同步失败</string>
   <string name="sync_fail_content"> %1$s同步未完成。</string>
+  <string name="sync_fail_content_unauthorized">密码错误%1$s</string>
   <string name="sync_conflicts_in_favourites_ticker">发现冲突</string>
   <string name="sync_conflicts_in_favourites_content">%1$d 文件无法同步</string>
   <string name="sync_fail_in_favourites_ticker">文件同步失败</string>
   <string name="sync_fail_in_favourites_content">无法同步 %1$d 文件内容(与 %2$d 冲突)</string>
   <string name="sync_foreign_files_forgotten_ticker">某些本地文件已被遗忘</string>
   <string name="sync_foreign_files_forgotten_content">%2$s目录中的%1$d个文件不能被复制到</string>
+  <string name="sync_foreign_files_forgotten_explanation">\"从 1.3.16 版起,从此设备上传的文件将被复制到本地的 %1$s 文件夹来防止当某个单一文件在多个账户间同步造成的数据损失。由于此项变化,此应用之前的版本上传的全部文件都已被复制到了 %2$s 文件夹。然而,账户同步期间有一个错误阻止了此操作的完成。您或许可以保持文件不动,并移除指向 %3$s 的链接,或将文件移动到 %1$s 文件夹中并将保持到 %4$s 的链接。下面列出的是本地文件,以及它们被链接到的 %5$s 中的远程文件。</string>
   <string name="foreign_files_move">移动所有</string>
   <string name="foreign_files_success">所有文件已被移动</string>
   <string name="foreign_files_fail">某些文件无法被移动</string>
   <string name="auth_bad_oc_version_title">不可辨识的owncloud服务器版本</string>
   <string name="auth_wrong_connection_title">无法建立连接</string>
   <string name="auth_secure_connection">加密连接已建立</string>
+  <string name="auth_unauthorized">用户名或密码错误!</string>
   <string name="auth_not_found">错误的路径</string>
   <string name="auth_internal">内部服务器错误,代码 %1$d</string>
+  <string name="auth_expired_basic_auth_toast">请输入当前密码:</string>
   <string name="crashlog_message">应用崩溃,是否提交崩溃报告?</string>
   <string name="crashlog_send_report">发送报告</string>
   <string name="crashlog_dont_send_report">不发送报告</string>
index 4e5d310..17333b7 100644 (file)
   <string name="main_settings">設定</string>
   <string name="main_tit_accsetup">設定帳號</string>
   <string name="main_wrn_accsetup">您尚未在裝置上設定您的 ownCloud 帳號,您必需建立一組帳號才能繼續使用。</string>
+  <string name="about_android">%1$s Android 應用程式</string>
+  <string name="about_version">版本 %1$s</string>
+  <string name="actionbar_sync">更新檔案列表</string>
   <string name="actionbar_upload">上傳檔案</string>
   <string name="actionbar_upload_from_apps">其他應用程序的內容</string>
   <string name="actionbar_upload_files">檔案</string>
+  <string name="actionbar_open_with">開啟方式</string>
   <string name="actionbar_mkdir">建立目錄</string>
   <string name="actionbar_search">搜尋</string>
   <string name="actionbar_settings">設定</string>
+  <string name="actionbar_see_details">詳細資料</string>
   <string name="prefs_category_general">一般</string>
   <string name="prefs_add_session">增加新連線</string>
   <string name="prefs_create_img_thumbnails">建立圖片縮圖</string>
   <string name="prefs_trackmydevice_interval_summary">每 %1$s 分鐘更新</string>
   <string name="prefs_accounts">帳號</string>
   <string name="prefs_manage_accounts">管理帳號</string>
+  <string name="prefs_pincode">App 密碼</string>
   <string name="prefs_pincode_summary">保護您的ownCloud用戶端</string>
   <string name="prefs_instant_upload">啟用即時上傳</string>
+  <string name="prefs_instant_upload_summary">即時上傳照相機拍攝的圖片</string>
+  <string name="prefs_log_title">啟用記錄</string>
+  <string name="prefs_log_summary">這個用來記錄執行的動作以找出問題點</string>
+  <string name="prefs_log_title_history">歷史記錄</string>
+  <string name="prefs_log_summary_history">顯示之前的記錄檔</string>
+  <string name="prefs_log_delete_history_button">刪除歷史記錄</string>
+  <string name="auth_check_server">檢查伺服器</string>
   <string name="auth_host_url">伺服器位址</string>
   <string name="auth_username">使用者名稱</string>
   <string name="auth_password">密碼</string>
+  <string name="auth_register">新增到 %1$s?</string>
   <string name="new_session_uri_error">錯誤的位址</string>
   <string name="new_session_session_name_error">錯誤的連線名稱</string>
   <string name="sync_string_files">檔案</string>
   <string name="setup_title">連線至您的 %1$s</string>
   <string name="setup_btn_connect">連線</string>
   <string name="uploader_btn_upload_text">上傳</string>
+  <string name="uploader_top_message">選取上傳目錄:</string>
   <string name="uploader_wrn_no_account_title">找不到帳號</string>
   <string name="uploader_wrn_no_account_text">在您的裝置上找不到ownCloud的帳號. 請先設定一組帳號.</string>
   <string name="uploader_wrn_no_account_setup_btn_text">設定</string>
   <string name="uploader_wrn_no_account_quit_btn_text">離開</string>
   <string name="uploader_wrn_no_content_title">沒有上載的內容</string>
   <string name="uploader_wrn_no_content_text">沒接到任何內容。沒有什麼可上載。</string>
+  <string name="uploader_error_forbidden_content">%1$s 並沒有被允許存取分享的內容</string>
   <string name="uploader_info_uploading">上傳中</string>
   <string name="uploader_btn_create_dir_text">建立上傳目錄</string>
+  <string name="file_list_empty">這個目錄目前是空的</string>
   <string name="filedetails_select_file">在檔案上輕觸來顯示更多資訊。</string>
   <string name="filedetails_size">容量:</string>
   <string name="filedetails_type">類型:</string>
   <string name="filedetails_created">建立:</string>
   <string name="filedetails_modified">修改:</string>
   <string name="filedetails_download">下載</string>
+  <string name="filedetails_sync_file">更新檔案列表</string>
   <string name="filedetails_redownload">重新下載</string>
+  <string name="filedetails_renamed_in_upload_msg">檔案名稱在上傳時已被更改為 %1$s</string>
   <string name="common_yes">是</string>
   <string name="common_no">否</string>
   <string name="common_ok">好</string>
@@ -71,6 +90,7 @@
   <string name="common_save_exit">儲存並離開</string>
   <string name="common_exit">離開ownCloud</string>
   <string name="common_error">錯誤</string>
+  <string name="common_loading">載入 …</string>
   <string name="common_error_unknown">未知的錯誤</string>
   <string name="about_title">關於</string>
   <string name="change_password">變更密碼</string>
   <string name="upload_chooser_title">更新自 ...</string>
   <string name="uploader_info_dirname">目錄名稱</string>
   <string name="uploader_upload_in_progress_ticker">更新中 ...</string>
+  <string name="uploader_upload_in_progress_content">%1$d%% 上傳中 %2$s</string>
   <string name="uploader_upload_succeeded_ticker">更新成功</string>
   <string name="uploader_upload_succeeded_content_single">%1$s 已成功地上傳</string>
   <string name="uploader_upload_succeeded_content_multiple">%1$d 檔案已成功地上傳</string>
   <string name="uploader_upload_failed_ticker">上傳失敗</string>
+  <string name="uploader_upload_failed_content_single">上傳 %1$s 未完成</string>
+  <string name="uploader_upload_failed_content_multiple">上傳失敗: %1$d/%2$d 檔案已上傳</string>
   <string name="downloader_download_in_progress_ticker">下載中 ...</string>
+  <string name="downloader_download_in_progress_content">%1$d%% 下載中 %2$s</string>
   <string name="downloader_download_succeeded_ticker">下載成功</string>
+  <string name="downloader_download_succeeded_content">%1$s 已成功下載</string>
   <string name="downloader_download_failed_ticker">下載失敗</string>
+  <string name="downloader_download_failed_content">下載 %1$s 未完成</string>
+  <string name="downloader_not_downloaded_yet">尚未下載</string>
   <string name="common_choose_account">選擇帳號</string>
   <string name="sync_string_contacts">通訊錄</string>
   <string name="sync_fail_ticker">同步失敗</string>
+  <string name="sync_fail_content">同步 %1$s 未完成</string>
+  <string name="sync_fail_content_unauthorized">無效的密碼 %1$s</string>
   <string name="sync_conflicts_in_favourites_ticker">出現衝突</string>
+  <string name="sync_conflicts_in_favourites_content">%1$d 持續同步未被同步的檔案</string>
+  <string name="sync_fail_in_favourites_ticker">同步檔案失敗</string>
+  <string name="sync_fail_in_favourites_content">%1$d 未被同步 (%2$d 衝突)</string>
+  <string name="sync_foreign_files_forgotten_ticker">有些本地端的檔案已遺失</string>
+  <string name="sync_foreign_files_forgotten_content">%1$d 檔案於 %2$s 目錄未被複製</string>
+  <string name="sync_foreign_files_forgotten_explanation">在 1.3.16 之前, 檔案上傳到本地的 %1$s 目錄以避免在多帳戶內同步造成遺失.\n\n由於這個改變, 所以在之前版本上傳的檔案被複製到 %2$s 目錄中. 為了避免同步發生問題. 你可以保留那些檔案並刪除連結 %3$s, 或搬移檔案到 %1$s 目錄並取得連結到 %4$s.\n\n下面列表是本地檔案, 與被連結遠端檔案 %5$s.</string>
   <string name="foreign_files_move">移動全部</string>
   <string name="foreign_files_success">所有文件已被移動</string>
-  <string name="foreign_files_fail">一些文件無法移動</string>
+  <string name="foreign_files_fail">部份文件無法被移動</string>
+  <string name="foreign_files_local_text">本地: %1$s</string>
+  <string name="foreign_files_remote_text">遠端: %1$s</string>
+  <string name="upload_query_move_foreign_files">無足夠的空間可以複製檔案到 %1$s 目錄. 是否使用移動的方式來處理? </string>
   <string name="use_ssl">使用安全連線</string>
   <string name="location_no_provider">%1$s 無法追蹤您的裝置,請檢查定位服務設定</string>
-  <string name="pincode_enter_pin_code">請輸入您的 App PIN</string>
-  <string name="pincode_enter_new_pin_code">請輸入您的新 App PIN</string>
-  <string name="pincode_configure_your_pin">輸入您的 App PIN</string>
-  <string name="pincode_reenter_your_pincode">請重新輸入您的 App PIN</string>
-  <string name="pincode_remove_your_pincode">移除您的 App PIN</string>
-  <string name="pincode_mismatch">App PIN 不相符</string>
-  <string name="pincode_wrong">App PIN 不正確</string>
-  <string name="pincode_removed">App PIN 已移除</string>
-  <string name="pincode_stored">App PIN 已儲存</string>
+  <string name="pincode_enter_pin_code">請輸入您的 App 密碼</string>
+  <string name="pincode_enter_new_pin_code">請輸入您的新 App 密碼</string>
+  <string name="pincode_configure_your_pin">輸入您的 App 密碼</string>
+  <string name="pincode_configure_your_pin_explanation">這個密碼在你每次啟動這程式時都會被要求輸入</string>
+  <string name="pincode_reenter_your_pincode">請重新輸入您的 App 密碼</string>
+  <string name="pincode_remove_your_pincode">移除您的 App 密碼</string>
+  <string name="pincode_mismatch">App 密碼不相符</string>
+  <string name="pincode_wrong">App 密碼不正確</string>
+  <string name="pincode_removed">App 密碼已移除</string>
+  <string name="pincode_stored">App 密碼已儲存</string>
+  <string name="media_notif_ticker">%1$s 音樂播放器</string>
+  <string name="media_state_playing">%1$s (播放中)</string>
+  <string name="media_state_loading">%1$s (載入中)</string>
+  <string name="media_event_done">%1$s 已播放</string>
+  <string name="media_err_nothing_to_play">沒有發現音樂媒體</string>
+  <string name="media_err_no_account">沒有提供的帳戶</string>
+  <string name="media_err_not_in_owncloud">檔案不存在於有效的帳戶中</string>
+  <string name="media_err_unsupported">未支援的媒體編碼</string>
+  <string name="media_err_io">無法讀取媒體檔案</string>
+  <string name="media_err_malformed">媒體檔案未被正確的編碼</string>
+  <string name="media_err_timeout">太多次嘗試播放</string>
+  <string name="media_err_invalid_progressive_playback">媒體檔案無法在網路播放</string>
+  <string name="media_err_unknown">媒體檔案無法在正常的播放軟體播放</string>
+  <string name="media_err_security_ex">在播放 %1$s 時發生安全性的錯誤</string>
+  <string name="media_err_io_ex">在播放 %1$s 時發生輸入錯誤</string>
+  <string name="media_err_unexpected">在播放 %1$s 時發生未知的錯誤</string>
+  <string name="media_previous_description">回到上一首按鍵</string>
+  <string name="media_rewind_description">重新播放按鍵</string>
+  <string name="media_play_pause_description">播放或暫停按鍵</string>
+  <string name="media_forward_description">快轉按鍵</string>
+  <string name="media_next_description">下一首按鍵</string>
   <string-array name="prefs_trackmydevice_intervall_keys">
     <item>15 分鐘</item>
     <item>30 分鐘</item>
     <item>30</item>
     <item>60</item>
   </string-array>
+  <string name="auth_trying_to_login">嘗試登入…</string>
   <string name="auth_no_net_conn_title">沒有網際網路連線</string>
   <string name="auth_no_net_conn_message">沒有偵測到網際網路連線,請檢查您的連線然後再試一次。</string>
   <string name="auth_connect_anyway">繼續連線</string>
   <string name="auth_nossl_plain_ok_title">安全連線不可用。</string>
   <string name="auth_nossl_plain_ok_message">無法與伺服器建立安全連線,可以使用不安全連線(未加密)以繼續,您可以繼續或取消。</string>
   <string name="auth_connection_established">連線已建立</string>
+  <string name="auth_testing_connection">測試連線中…</string>
   <string name="auth_not_configured_title">伺服器設定有問題</string>
   <string name="auth_not_configured_message">看起來您的伺服器並未被正確設定,請聯絡服務管理者以取得協助。</string>
   <string name="auth_unknown_error_title">發生未知的錯誤!</string>
   <string name="auth_unknown_error_message">發生未知的錯誤,請聯絡支援服務並附上您的記錄檔。</string>
   <string name="auth_unknown_host_title">找不到伺服器</string>
+  <string name="auth_unknown_host_message">無法找到伺服器. 請檢查是否正確輸入並再試一次.</string>
   <string name="auth_incorrect_path_title">找不到伺服器</string>
   <string name="auth_incorrect_path_message">在指定的路徑找不到伺服器,請檢查您的路徑然後再試一次。</string>
   <string name="auth_timeout_title">伺服器回應逾時</string>
   <string name="auth_bad_oc_version_title">無法辨識的ownCloud伺服器版本</string>
   <string name="auth_wrong_connection_title">無法建立連線</string>
   <string name="auth_secure_connection">安全連線已建立</string>
+  <string name="auth_unauthorized">錯誤的使用者或密碼</string>
+  <string name="auth_oauth_error">未成功登入</string>
+  <string name="auth_oauth_error_access_denied">被授登伺服器拒絕登入</string>
+  <string name="auth_not_found"> 錯誤的路徑</string>
+  <string name="auth_internal">內部錯誤, 代碼 %1$d</string>
+  <string name="auth_wtf_reenter_URL">未知的狀態; 請再輸入一次伺服器的名稱</string>
+  <string name="auth_expired_oauth_token_toast">你的登入授權已過期.\n請再次登入</string>
+  <string name="auth_expired_basic_auth_toast">請輸入目錄的密碼</string>
+  <string name="crashlog_message">程式未預期的錯誤. 你要寄送錯誤的分析報告嗎?</string>
   <string name="crashlog_send_report">發送報告</string>
   <string name="crashlog_dont_send_report">不要發送報告</string>
+  <string name="extensions_avail_title">延伸功能可以使用!</string>
+  <string name="extensions_avail_message">你的伺服器支援某些延伸功能. 你是否要使用他們?</string>
   <string name="fd_keep_in_sync">讓檔案保持最新的</string>
   <string name="common_share">分享</string>
   <string name="common_rename">重新命名</string>
   <string name="common_remove">移除</string>
   <string name="confirmation_remove_alert">您真的要移除 %1$s ?</string>
+  <string name="confirmation_remove_folder_alert">您真的要移除 %1$s 與裡頭的檔案?</string>
   <string name="confirmation_remove_local">只有本地</string>
+  <string name="confirmation_remove_folder_local">只有本地</string>
   <string name="confirmation_remove_remote">從伺服器移除</string>
+  <string name="confirmation_remove_remote_and_local">遠端與本地</string>
   <string name="remove_success_msg">成功地移除</string>
+  <string name="remove_fail_msg">刪除失敗</string>
   <string name="rename_dialog_title">輸入新名稱</string>
   <string name="rename_local_fail_msg">本地的複本無法被重新命名; 請嘗試一個不同的新名稱</string>
   <string name="rename_server_fail_msg">重新命名失敗</string>
+  <string name="sync_file_fail_msg">無法檢查遠端的檔案</string>
+  <string name="sync_file_nothing_to_do_msg">檔案與同步</string>
   <string name="create_dir_fail_msg">資料夾無法被建立</string>
   <string name="wait_a_moment">請稍後</string>
+  <string name="filedisplay_unexpected_bad_get_content">未知的問題; 請選擇其他程式開啟檔案</string>
   <string name="filedisplay_no_file_selected">沒有挑選檔案</string>
+  <string name="oauth_host_url">oAuth2 網址</string>
+  <string name="oauth_check_onoff">以 oAuth2 方式登入.</string>
+  <string name="oauth_login_connection">連線到 oAuth2 伺服器…</string>
+  <string name="oauth_code_validation_message">請打開瀏覽器連到:\n%1$s.\n檢查碼為:\n%2$s</string>
+  <string name="oauth_connection_url_unavailable">無法連線到該網址.</string>
   <string name="ssl_validator_title">警告</string>
+  <string name="ssl_validator_header">這個網站的憑證無法被驗證</string>
+  <string name="ssl_validator_reason_cert_not_trusted">- 這個伺服器使用未被信任的憑證</string>
+  <string name="ssl_validator_reason_cert_expired">- 這個伺服器的憑證已過期</string>
+  <string name="ssl_validator_reason_cert_not_yet_valid">- 這個伺服器的憑證有效期限不正確</string>
+  <string name="ssl_validator_reason_hostname_not_verified">- 這個伺服器的憑證與使用的伺服器名稱不一樣</string>
+  <string name="ssl_validator_certificate_not_available">無法取得伺服器的憑證</string>
+  <string name="ssl_validator_question">你是否要信任這個伺服器的憑證?</string>
+  <string name="ssl_validator_not_saved">無法儲存憑證</string>
   <string name="ssl_validator_btn_details_see">細節</string>
   <string name="ssl_validator_btn_details_hide">隱藏</string>
+  <string name="ssl_validator_label_subject">發行給:</string>
+  <string name="ssl_validator_label_issuer">發行者:</string>
+  <string name="ssl_validator_label_CN">網站:</string>
   <string name="ssl_validator_label_O">組織:</string>
   <string name="ssl_validator_label_OU">組織部門:</string>
   <string name="ssl_validator_label_C">國家:</string>
   <string name="ssl_validator_label_ST">省:</string>
   <string name="ssl_validator_label_L">地點:</string>
+  <string name="ssl_validator_label_validity">有效期限:</string>
   <string name="ssl_validator_label_validity_from">從:</string>
   <string name="ssl_validator_label_validity_to">至:</string>
   <string name="ssl_validator_label_signature">簽名:</string>
+  <string name="ssl_validator_label_signature_algorithm">演算法:</string>
+  <string name="placeholder_sentence">這是佔位的資訊</string>
+  <string name="placeholder_filename">placeholder.txt</string>
+  <string name="placeholder_filetype">PNG 圖檔</string>
+  <string name="placeholder_filesize">389 KB</string>
+  <string name="placeholder_timestamp">2012/05/18 12:23 PM</string>
+  <string name="placeholder_media_time">12:23:45</string>
+  <string name="instant_upload_on_wifi">只使用 WiFi 上傳</string>
+  <string name="instant_upload_path">/InstantUpload</string>
   <string name="conflict_title">更新衝突</string>
+  <string name="conflict_message">遠端檔案 %s 未同步到本地. 繼續將取代伺服器上的文件.</string>
   <string name="conflict_keep_both">都保留</string>
   <string name="conflict_overwrite">覆寫</string>
   <string name="conflict_dont_upload">不要上載</string>
+  <string name="preview_image_description">圖片預覽</string>
+  <string name="preview_image_error_unknown_format">無法顯示圖片</string>
+  <string name="preview_image_error_out_of_memory">\"沒有足夠的記憶體來顯示圖片</string>
   <!--we need to improve the communication of errors to the user-->
+  <string name="error__upload__local_file_not_copied">%1$s 無法被複製到本地目錄 %2$s</string>
+  <string name="actionbar_failed_instant_upload">即時上傳失敗</string>
+  <string name="failed_upload_headline_text">即時上傳失敗</string>
+  <string name="failed_upload_headline_hint">所有即時上傳失敗的記錄</string>
+  <string name="failed_upload_all_cb">全部選取</string>
+  <string name="failed_upload_headline_retryall_btn">重新上傳選取的檔案</string>
+  <string name="failed_upload_headline_delete_all_btn">刪除所有被選取的檔案</string>
+  <string name="failed_upload_retry_text">重新上傳這個檔案: </string>
+  <string name="failed_upload_load_more_images">載入更多的檔案</string>
+  <string name="failed_upload_retry_do_nothing_text">未連線, 所以無法使用上傳功能</string>
+  <string name="failed_upload_failure_text">失敗訊息: </string>
+  <string name="failed_upload_quota_exceeded_text">請檢查你的伺服器設定, 可能你的額度已超過.</string>
 </resources>
diff --git a/res/values/branding.xml b/res/values/branding.xml
deleted file mode 100644 (file)
index f312dad..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
-    <string name="server_url"></string>
-    <bool name="show_server_url_input">true</bool>
-</resources>
index 5fbef7c..f8e0f51 100644 (file)
@@ -1,10 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
 <resources>
-    <!-- Flag to configure OAuth availability in the app.
-        3 valid values now: on, off, optional  
-     -->
-    <string name="oauth2_mode">off</string>
-    
     <!-- constants that must be respected by the authorization server; if changed, the app must be rebuild -->
     <string name="oauth2_redirect_scheme">owncloud</string>
     <string name="oauth2_redirect_uri">owncloud://callback</string>
diff --git a/res/values/setup.xml b/res/values/setup.xml
new file mode 100644 (file)
index 0000000..b3cb69b
--- /dev/null
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="server_url"></string>
+    <bool name="show_server_url_input">true</bool>
+    
+    <!-- Flags to setup the authentication methods available in the app -->
+    <string name="auth_method_oauth2">off</string>
+    <string name="auth_method_saml_web_sso">off</string>
+    
+</resources>
index 8c273bd..0872084 100644 (file)
@@ -49,6 +49,7 @@
     <string name="prefs_log_delete_history_button">Delete History</string>
     
     <string name="auth_check_server">Check Server</string>
+    <string name="auth_account_name">Account name</string>
     <string name="auth_host_url">Server address</string>
     <string name="auth_username">Username</string>
     <string name="auth_password">Password</string>
     <string name="auth_testing_connection">Testing connection&#8230;</string>
     <string name="auth_not_configured_title">Malformed server configuration</string>
     <string name="auth_not_configured_message">It seems that your server instance is not correctly configured. Contact your administrator for more details.</string>
+    <string name="auth_account_not_new">An account for the same user and server already exists in the device</string>
+    <string name="auth_account_not_the_same">The entered user does not match the user of this account</string>
     <string name="auth_unknown_error_title">Unknown error occurred!</string>
     <string name="auth_unknown_error_message">An unknown error occurred. Please contact support and include logs from your device.</string>
     <string name="auth_unknown_host_title">Couldn\'t find host</string>
     <string name="auth_not_found">Wrong path given</string>
     <string name="auth_internal">Internal server error, code %1$d</string>
     <string name="auth_wtf_reenter_URL">Unexpected state; please, enter the server URL again</string>
-    <string name="auth_expired_oauth_token_toast">Your authorization expired.\nPlease, authorize again</string>
+    <string name="auth_expired_oauth_token_toast">Your authorization expired. Please, authorize again</string>
     <string name="auth_expired_basic_auth_toast">Please, enter the current password</string>
+    <string name="auth_expired_saml_sso_token_toast">Your session expired. Please connect again</string>
+       <string name="auth_connecting_auth_server">Connecting to authentication server…</string>
+       <string name="auth_follow_auth_server">Follow instructions above to get authenticated</string>
+       <string name="auth_unsupported_auth_method">The server does not support this authentication method</string>    
     
     <string name="crashlog_message">Application terminated unexpectedly. Would you like to submit a crash report?</string>
     <string name="crashlog_send_report">Send report</string>
index 13d0ed2..3ad0151 100644 (file)
@@ -20,7 +20,7 @@
 <resources xmlns:android="http://schemas.android.com/apk/res/android">
        <style name="Animations" />
 
-       <!-- Default ownCloud app style -->
+       <!-- General ownCloud app style -->
        <style name="Theme.ownCloud" parent="style/Theme.Sherlock.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/Theme.ownCloud.Widget.ActionBar</item>
        <item name="actionBarStyle">@style/Theme.ownCloud.Widget.ActionBar</item>
        <item name="android:shadowDy">1</item>
        <item name="android:backgroundSplit">@drawable/split_action_bg</item>
        </style>
+
+               
+       <!-- Dialogs -->
+       <style name="Theme.ownCloud.Dialog" parent="style/Theme.Sherlock.Light.Dialog">
+       </style>
+       
        
        <!-- PopDownMenu -->
        <style name="Animations.PopDownMenu" />
index 30eda59..85e9a23 100644 (file)
@@ -46,6 +46,7 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
     public static final String AUTH_TOKEN_TYPE_PASSWORD = "owncloud.password";
     public static final String AUTH_TOKEN_TYPE_ACCESS_TOKEN = "owncloud.oauth2.access_token";
     public static final String AUTH_TOKEN_TYPE_REFRESH_TOKEN = "owncloud.oauth2.refresh_token";
+    public static final String AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE = "owncloud.saml.web_sso.session_cookie";
 
     public static final String KEY_AUTH_TOKEN_TYPE = "authTokenType";
     public static final String KEY_REQUIRED_FEATURES = "requiredFeatures";
@@ -75,6 +76,10 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
      * Flag signaling if the ownCloud server can be accessed with OAuth2 access tokens.
      */
     public static final String KEY_SUPPORTS_OAUTH2 = "oc_supports_oauth2";
+    /**
+     * Flag signaling if the ownCloud server can be accessed with session cookies from SAML-based web single-sign-on.
+     */
+    public static final String KEY_SUPPORTS_SAML_WEB_SSO = "oc_supports_saml_web_sso";
     
     private static final String TAG = AccountAuthenticator.class.getSimpleName();
     
@@ -254,7 +259,8 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
         if (!authTokenType.equals(AUTH_TOKEN_TYPE) &&\r
             !authTokenType.equals(AUTH_TOKEN_TYPE_PASSWORD) &&\r
             !authTokenType.equals(AUTH_TOKEN_TYPE_ACCESS_TOKEN) &&\r
-            !authTokenType.equals(AUTH_TOKEN_TYPE_REFRESH_TOKEN) ) {\r
+            !authTokenType.equals(AUTH_TOKEN_TYPE_REFRESH_TOKEN) &&
+            !authTokenType.equals(AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE)) {\r
             throw new UnsupportedAuthTokenTypeException();\r
         }\r
     }\r
diff --git a/src/com/owncloud/android/authentication/AccountAuthenticatorActivity.java b/src/com/owncloud/android/authentication/AccountAuthenticatorActivity.java
new file mode 100644 (file)
index 0000000..62c8825
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.owncloud.android.authentication;
+
+import android.accounts.AccountAuthenticatorResponse;
+import android.accounts.AccountManager;
+import android.os.Bundle;
+
+import com.actionbarsherlock.app.SherlockFragmentActivity;
+
+
+/*
+ * Base class for implementing an Activity that is used to help implement an AbstractAccountAuthenticator. 
+ * If the AbstractAccountAuthenticator needs to use an activity to handle the request then it can have the activity extend 
+ * AccountAuthenticatorActivity. The AbstractAccountAuthenticator passes in the response to the intent using the following:
+ * intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
+ * 
+ * The activity then sets the result that is to be handed to the response via setAccountAuthenticatorResult(android.os.Bundle). 
+ * This result will be sent as the result of the request when the activity finishes. If this is never set or if it is set to null 
+ * then error AccountManager.ERROR_CODE_CANCELED will be called on the response.
+ */
+
+public class AccountAuthenticatorActivity extends SherlockFragmentActivity {
+
+    private AccountAuthenticatorResponse mAccountAuthenticatorResponse = null;
+    private Bundle mResultBundle = null;
+
+
+    /**
+     * Set the result that is to be sent as the result of the request that caused this Activity to be launched.
+     * If result is null or this method is never called then the request will be canceled.
+     * 
+     * @param result this is returned as the result of the AbstractAccountAuthenticator request
+     */
+    public final void setAccountAuthenticatorResult(Bundle result) {
+        mResultBundle = result;
+    }
+
+    /**
+     * Retreives the AccountAuthenticatorResponse from either the intent of the icicle, if the
+     * icicle is non-zero.
+     * @param icicle the save instance data of this Activity, may be null
+     */
+    protected void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+
+        mAccountAuthenticatorResponse =
+                getIntent().getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
+
+        if (mAccountAuthenticatorResponse != null) {
+            mAccountAuthenticatorResponse.onRequestContinued();
+        }
+    }
+    
+    /**
+     * Sends the result or a Constants.ERROR_CODE_CANCELED error if a result isn't present.
+     */
+    public void finish() {
+        if (mAccountAuthenticatorResponse != null) {
+            // send the result bundle back if set, otherwise send an error.
+            if (mResultBundle != null) {
+                mAccountAuthenticatorResponse.onResult(mResultBundle);
+            } else {
+                mAccountAuthenticatorResponse.onError(AccountManager.ERROR_CODE_CANCELED,
+                        "canceled");
+            }
+            mAccountAuthenticatorResponse = null;
+        }
+        super.finish();
+    }
+}
index 591da01..47269bc 100644 (file)
@@ -32,6 +32,7 @@ public class AccountUtils {
     public static final String WEBDAV_PATH_2_0 = "/files/webdav.php";\r
     public static final String WEBDAV_PATH_4_0 = "/remote.php/webdav";\r
     private static final String ODAV_PATH = "/remote.php/odav";\r
+    private static final String SAML_SSO_PATH = "/remote.php/webdav";\r
     public static final String CARDDAV_PATH_2_0 = "/apps/contacts/carddav.php";\r
     public static final String CARDDAV_PATH_4_0 = "/remote/carddav.php";\r
     public static final String STATUS_PATH = "/status.php";\r
@@ -74,6 +75,20 @@ public class AccountUtils {
     }\r
 \r
     \r
+    public static boolean exists(Account account, Context context) {\r
+        Account[] ocAccounts = AccountManager.get(context).getAccountsByType(\r
+                AccountAuthenticator.ACCOUNT_TYPE);\r
+\r
+        if (account != null && account.name != null) {\r
+            for (Account ac : ocAccounts) {\r
+                if (ac.name.equals(account.name)) {\r
+                    return true;\r
+                }\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+    \r
 \r
     /**\r
      * Checks, whether or not there are any ownCloud accounts setup.\r
@@ -115,11 +130,41 @@ public class AccountUtils {
      * @param version version of owncloud\r
      * @return webdav path for given OC version, null if OC version unknown\r
      */\r
-    public static String getWebdavPath(OwnCloudVersion version, boolean supportsOAuth) {\r
+    public static String getWebdavPath(OwnCloudVersion version, boolean supportsOAuth, boolean supportsSamlSso) {\r
         if (version != null) {\r
             if (supportsOAuth) {\r
                 return ODAV_PATH;\r
             }\r
+            if (supportsSamlSso) {\r
+                return SAML_SSO_PATH;\r
+            }\r
+            if (version.compareTo(OwnCloudVersion.owncloud_v4) >= 0)\r
+                return WEBDAV_PATH_4_0;\r
+            if (version.compareTo(OwnCloudVersion.owncloud_v3) >= 0\r
+                    || version.compareTo(OwnCloudVersion.owncloud_v2) >= 0)\r
+                return WEBDAV_PATH_2_0;\r
+            if (version.compareTo(OwnCloudVersion.owncloud_v1) >= 0)\r
+                return WEBDAV_PATH_1_2;\r
+        }\r
+        return null;\r
+    }\r
+    \r
+    /**\r
+     * Returns the proper URL path to access the WebDAV interface of an ownCloud server,\r
+     * according to its version and the authorization method used.\r
+     * \r
+     * @param   version         Version of ownCloud server.\r
+     * @param   authTokenType   Authorization token type, matching some of the AUTH_TOKEN_TYPE_* constants in {@link AccountAuthenticator}. \r
+     * @return                  WebDAV path for given OC version and authorization method, null if OC version is unknown.\r
+     */\r
+    public static String getWebdavPath(OwnCloudVersion version, String authTokenType) {\r
+        if (version != null) {\r
+            if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(authTokenType)) {\r
+                return ODAV_PATH;\r
+            }\r
+            if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(authTokenType)) {\r
+                return SAML_SSO_PATH;\r
+            }\r
             if (version.compareTo(OwnCloudVersion.owncloud_v4) >= 0)\r
                 return WEBDAV_PATH_4_0;\r
             if (version.compareTo(OwnCloudVersion.owncloud_v3) >= 0\r
@@ -143,8 +188,9 @@ public class AccountUtils {
         String baseurl = ama.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL);\r
         String strver  = ama.getUserData(account, AccountAuthenticator.KEY_OC_VERSION);\r
         boolean supportsOAuth = (ama.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null);\r
+        boolean supportsSamlSso = (ama.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null);\r
         OwnCloudVersion ver = new OwnCloudVersion(strver);\r
-        String webdavpath = getWebdavPath(ver, supportsOAuth);\r
+        String webdavpath = getWebdavPath(ver, supportsOAuth, supportsSamlSso);\r
 \r
         if (baseurl == null || webdavpath == null) \r
             throw new AccountNotFoundException(account, "Account not found", null);\r
index 76041c1..e0d48a3 100644 (file)
 \r
 package com.owncloud.android.authentication;\r
 \r
-import com.owncloud.android.Log_OC;\r
-import com.owncloud.android.ui.dialog.SslValidatorDialog;\r
-import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;\r
-import com.owncloud.android.utils.OwnCloudVersion;\r
-import com.owncloud.android.network.OwnCloudClientUtils;\r
-import com.owncloud.android.operations.OwnCloudServerCheckOperation;\r
-import com.owncloud.android.operations.ExistenceCheckOperation;\r
-import com.owncloud.android.operations.OAuth2GetAccessToken;\r
-import com.owncloud.android.operations.OnRemoteOperationListener;\r
-import com.owncloud.android.operations.RemoteOperation;\r
-import com.owncloud.android.operations.RemoteOperationResult;\r
-import com.owncloud.android.operations.RemoteOperationResult.ResultCode;\r
-\r
 import android.accounts.Account;\r
-import android.accounts.AccountAuthenticatorActivity;\r
 import android.accounts.AccountManager;\r
 import android.app.AlertDialog;\r
 import android.app.Dialog;\r
@@ -47,6 +33,7 @@ import android.net.Uri;
 import android.os.Bundle;\r
 import android.os.Handler;\r
 import android.preference.PreferenceManager;\r
+import android.support.v4.app.Fragment;\r
 import android.text.Editable;\r
 import android.text.InputType;\r
 import android.text.TextWatcher;\r
@@ -57,14 +44,28 @@ import android.view.View.OnFocusChangeListener;
 import android.view.View.OnTouchListener;\r
 import android.view.Window;\r
 import android.view.inputmethod.EditorInfo;\r
+import android.widget.Button;\r
 import android.widget.CheckBox;\r
 import android.widget.EditText;\r
-import android.widget.Button;\r
 import android.widget.TextView;\r
-import android.widget.Toast;\r
 import android.widget.TextView.OnEditorActionListener;\r
 \r
+import com.actionbarsherlock.app.SherlockDialogFragment;\r
+import com.owncloud.android.Log_OC;\r
 import com.owncloud.android.R;\r
+import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;\r
+import com.owncloud.android.network.OwnCloudClientUtils;\r
+import com.owncloud.android.operations.ExistenceCheckOperation;\r
+import com.owncloud.android.operations.OAuth2GetAccessToken;\r
+import com.owncloud.android.operations.OnRemoteOperationListener;\r
+import com.owncloud.android.operations.OwnCloudServerCheckOperation;\r
+import com.owncloud.android.operations.RemoteOperation;\r
+import com.owncloud.android.operations.RemoteOperationResult;\r
+import com.owncloud.android.operations.RemoteOperationResult.ResultCode;\r
+import com.owncloud.android.ui.dialog.SamlWebViewDialog;\r
+import com.owncloud.android.ui.dialog.SslValidatorDialog;\r
+import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;\r
+import com.owncloud.android.utils.OwnCloudVersion;\r
 \r
 import eu.alefzero.webdav.WebdavClient;\r
 \r
@@ -75,7 +76,7 @@ import eu.alefzero.webdav.WebdavClient;
  * @author David A. Velasco\r
  */\r
 public class AuthenticatorActivity extends AccountAuthenticatorActivity\r
-implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeListener, OnEditorActionListener {\r
+implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeListener, OnEditorActionListener, SsoWebViewClientListener{\r
 \r
     private static final String TAG = AuthenticatorActivity.class.getSimpleName();\r
 \r
@@ -85,6 +86,8 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     public static final String EXTRA_ACTION = "ACTION";\r
     public static final String EXTRA_ENFORCED_UPDATE = "ENFORCE_UPDATE";\r
 \r
+    private static final String KEY_AUTH_MESSAGE_VISIBILITY = "AUTH_MESSAGE_VISIBILITY";\r
+    private static final String KEY_AUTH_MESSAGE_TEXT = "AUTH_MESSAGE_TEXT";\r
     private static final String KEY_HOST_URL_TEXT = "HOST_URL_TEXT";\r
     private static final String KEY_OC_VERSION = "OC_VERSION";\r
     private static final String KEY_ACCOUNT = "ACCOUNT";\r
@@ -98,11 +101,13 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     private static final String KEY_AUTH_STATUS_TEXT = "AUTH_STATUS_TEXT";\r
     private static final String KEY_AUTH_STATUS_ICON = "AUTH_STATUS_ICON";\r
     private static final String KEY_REFRESH_BUTTON_ENABLED = "KEY_REFRESH_BUTTON_ENABLED";\r
+    \r
+    private static final String KEY_OC_USERNAME_EQUALS = "oc_username=";\r
 \r
-    private static final String OAUTH_MODE_ON = "on";\r
-    private static final String OAUTH_MODE_OFF = "off";\r
-    private static final String OAUTH_MODE_OPTIONAL = "optional";\r
-\r
+    private static final String AUTH_ON = "on";\r
+    private static final String AUTH_OFF = "off";\r
+    private static final String AUTH_OPTIONAL = "optional";\r
+    \r
     private static final int DIALOG_LOGIN_PROGRESS = 0;\r
     private static final int DIALOG_SSL_VALIDATOR = 1;\r
     private static final int DIALOG_CERT_NOT_SAVED = 2;\r
@@ -111,12 +116,16 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     public static final byte ACTION_CREATE = 0;\r
     public static final byte ACTION_UPDATE_TOKEN = 1;\r
 \r
+    private static final String TAG_SAML_DIALOG = "samlWebViewDialog";\r
+    \r
     private String mHostBaseUrl;\r
     private OwnCloudVersion mDiscoveredVersion;\r
 \r
-    private int mServerStatusText, mServerStatusIcon;\r
+    private String mAuthMessageText;\r
+    private int mAuthMessageVisibility, mServerStatusText, mServerStatusIcon;\r
     private boolean mServerIsChecked, mServerIsValid, mIsSslConn;\r
     private int mAuthStatusText, mAuthStatusIcon;    \r
+    private TextView mAuthStatusLayout;\r
 \r
     private final Handler mHandler = new Handler();\r
     private Thread mOperationThread;\r
@@ -131,21 +140,29 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     private byte mAction;\r
     private Account mAccount;\r
 \r
+    private TextView mAuthMessage;\r
+    \r
     private EditText mHostUrlInput;\r
+    private boolean mHostUrlInputEnabled;\r
     private View mRefreshButton;\r
+\r
+    private String mAuthTokenType;\r
+    \r
     private EditText mUsernameInput;\r
     private EditText mPasswordInput;\r
+    \r
     private CheckBox mOAuth2Check;\r
-    private String mOAuthAccessToken;\r
-    private View mOkButton;\r
-    private TextView mAuthStatusLayout;\r
-\r
+    \r
     private TextView mOAuthAuthEndpointText;\r
     private TextView mOAuthTokenEndpointText;\r
     \r
-    private boolean mRefreshButtonEnabled;\r
+    private SamlWebViewDialog mSamlDialog;\r
     \r
-    private boolean mHostUrlInputEnabled;\r
+    private View mOkButton;\r
+    \r
+    private String mAuthToken;\r
+    \r
+    private boolean mResumed; // Control if activity is resumed\r
 \r
 \r
     /**\r
@@ -160,6 +177,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 \r
         /// set view and get references to view elements\r
         setContentView(R.layout.account_setup);\r
+        mAuthMessage = (TextView) findViewById(R.id.auth_message);\r
         mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput);\r
         mHostUrlInput.setText(getString(R.string.server_url));  // valid although R.string.server_url is an empty string\r
         mUsernameInput = (EditText) findViewById(R.id.account_username);\r
@@ -199,7 +217,9 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         }\r
 \r
         if (savedInstanceState == null) {\r
+            mResumed = false;\r
             /// connection state and info\r
+            mAuthMessageVisibility = View.GONE;\r
             mServerStatusText = mServerStatusIcon = 0;\r
             mServerIsValid = false;\r
             mServerIsChecked = false;\r
@@ -207,9 +227,6 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             mAuthStatusText = mAuthStatusIcon = 0;\r
 \r
             /// retrieve extras from intent\r
-            String tokenType = getIntent().getExtras().getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);\r
-            boolean oAuthRequired = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(tokenType) || OAUTH_MODE_ON.equals(getString(R.string.oauth2_mode));\r
-\r
             mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);\r
             if (mAccount != null) {\r
                 String ocVersion = mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);\r
@@ -220,18 +237,19 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
                 mHostUrlInput.setText(mHostBaseUrl);\r
                 String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));\r
                 mUsernameInput.setText(userName);\r
-                oAuthRequired = (mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null);\r
             }\r
-            mOAuth2Check.setChecked(oAuthRequired);\r
-            changeViewByOAuth2Check(oAuthRequired);\r
+            initAuthorizationMethod();  // checks intent and setup.xml to determine mCurrentAuthorizationMethod\r
             mJustCreated = true;\r
             \r
             if (mAction == ACTION_UPDATE_TOKEN || !mHostUrlInputEnabled) {\r
                 checkOcServer(); \r
             }\r
-\r
+            \r
         } else {\r
+            mResumed = true;\r
             /// connection state and info\r
+            mAuthMessageVisibility = savedInstanceState.getInt(KEY_AUTH_MESSAGE_VISIBILITY);\r
+            mAuthMessageText = savedInstanceState.getString(KEY_AUTH_MESSAGE_TEXT);\r
             mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID);\r
             mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED);\r
             mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT);\r
@@ -252,6 +270,11 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 \r
             // account data, if updating\r
             mAccount = savedInstanceState.getParcelable(KEY_ACCOUNT);\r
+            mAuthTokenType = savedInstanceState.getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);\r
+            if (mAuthTokenType == null) {\r
+                mAuthTokenType =  AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;\r
+                \r
+            }\r
 \r
             // check if server check was interrupted by a configuration change\r
             if (savedInstanceState.getBoolean(KEY_SERVER_CHECK_IN_PROGRESS, false)) {\r
@@ -264,9 +287,16 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 \r
         }\r
 \r
+        if (mAuthMessageVisibility== View.VISIBLE) {\r
+            showAuthMessage(mAuthMessageText);\r
+        }\r
+        else {\r
+            hideAuthMessage();\r
+        }\r
+        adaptViewAccordingToAuthenticationMethod();\r
         showServerStatus();\r
         showAuthStatus();\r
-\r
+        \r
         if (mAction == ACTION_UPDATE_TOKEN) {\r
             /// lock things that should not change\r
             mHostUrlInput.setEnabled(false);\r
@@ -280,14 +310,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         if (mServerIsChecked && !mServerIsValid && refreshButtonEnabled) showRefreshButton();\r
         mOkButton.setEnabled(mServerIsValid); // state not automatically recovered in configuration changes\r
 \r
-        if (!OAUTH_MODE_OPTIONAL.equals(getString(R.string.oauth2_mode))) {\r
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType) || \r
+                !AUTH_OPTIONAL.equals(getString(R.string.auth_method_oauth2))) {\r
             mOAuth2Check.setVisibility(View.GONE);\r
         }\r
 \r
         mPasswordInput.setText("");     // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)\r
 \r
-        /// bind view elements to listeners\r
+        /// bind view elements to listeners and other friends\r
         mHostUrlInput.setOnFocusChangeListener(this);\r
+        mHostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);\r
+        mHostUrlInput.setOnEditorActionListener(this);\r
         mHostUrlInput.addTextChangedListener(new TextWatcher() {\r
 \r
             @Override\r
@@ -298,12 +331,20 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             }\r
 \r
             @Override\r
-            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}\r
+            public void beforeTextChanged(CharSequence s, int start, int count, int after) {\r
+            }\r
 \r
             @Override\r
-            public void onTextChanged(CharSequence s, int start, int before, int count) {}\r
-\r
+            public void onTextChanged(CharSequence s, int start, int before, int count) {\r
+                if (!mResumed) {\r
+                    mAuthStatusIcon = 0;\r
+                    mAuthStatusText = 0;\r
+                    showAuthStatus();                    \r
+                }\r
+                mResumed = false;\r
+            }\r
         });\r
+        \r
         mPasswordInput.setOnFocusChangeListener(this);\r
         mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE);\r
         mPasswordInput.setOnEditorActionListener(this);
@@ -315,7 +356,60 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
                 }\r
                 return true;\r
             }\r
-        });
+        });\r
+        \r
+        findViewById(R.id.scroll).setOnTouchListener(new OnTouchListener() {\r
+            @Override\r
+            public boolean onTouch(View view, MotionEvent event) {\r
+                if (event.getAction() == MotionEvent.ACTION_DOWN) {\r
+                    if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType) &&\r
+                            mHostUrlInput.hasFocus()) {\r
+                        checkOcServer();\r
+                    }\r
+                }\r
+                return false;\r
+            }\r
+        });\r
+    }\r
+    \r
+   \r
+\r
+    private void initAuthorizationMethod() {\r
+        boolean oAuthRequired = false;\r
+        boolean samlWebSsoRequired = false;\r
+\r
+        mAuthTokenType = getIntent().getExtras().getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);\r
+        mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);\r
+        \r
+        // TODO could be a good moment to validate the received token type, if not null\r
+        \r
+        if (mAuthTokenType == null) {    \r
+            if (mAccount != null) {\r
+                /// same authentication method than the one used to create the account to update\r
+                oAuthRequired = (mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null);\r
+                samlWebSsoRequired = (mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null);\r
+            \r
+            } else {\r
+                /// use the one set in setup.xml\r
+                oAuthRequired = AUTH_ON.equals(getString(R.string.auth_method_oauth2));\r
+                samlWebSsoRequired = AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso));            \r
+            }\r
+            if (oAuthRequired) {\r
+                mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN;\r
+            } else if (samlWebSsoRequired) {\r
+                mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE;\r
+            } else {\r
+                mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;\r
+            }\r
+        }\r
+    \r
+        if (mAccount != null) {\r
+            String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));\r
+            mUsernameInput.setText(userName);\r
+        }\r
+        \r
+        mOAuth2Check.setChecked(AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType));\r
+        \r
     }\r
 \r
     /**\r
@@ -331,6 +425,8 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         super.onSaveInstanceState(outState);\r
 \r
         /// connection state and info\r
+        outState.putInt(KEY_AUTH_MESSAGE_VISIBILITY, mAuthMessage.getVisibility());\r
+        outState.putString(KEY_AUTH_MESSAGE_TEXT, mAuthMessage.getText().toString());\r
         outState.putInt(KEY_SERVER_STATUS_TEXT, mServerStatusText);\r
         outState.putInt(KEY_SERVER_STATUS_ICON, mServerStatusIcon);\r
         outState.putBoolean(KEY_SERVER_VALID, mServerIsValid);\r
@@ -351,10 +447,11 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         if (mAccount != null) {\r
             outState.putParcelable(KEY_ACCOUNT, mAccount);\r
         }\r
+        outState.putString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE, mAuthTokenType);\r
         \r
         // refresh button enabled\r
-        //outState.putBoolean(KEY_REFRESH_BUTTON_ENABLED, mRefreshButtonEnabled);\r
         outState.putBoolean(KEY_REFRESH_BUTTON_ENABLED, (mRefreshButton.getVisibility() == View.VISIBLE));\r
+        \r
 \r
     }\r
 \r
@@ -383,13 +480,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     @Override\r
     protected void onResume() {\r
         super.onResume();\r
-        // the state of mOAuth2Check is automatically recovered between configuration changes, but not before onCreate() finishes; so keep the next lines here\r
-        changeViewByOAuth2Check(mOAuth2Check.isChecked());  \r
         if (mAction == ACTION_UPDATE_TOKEN && mJustCreated && getIntent().getBooleanExtra(EXTRA_ENFORCED_UPDATE, false)) {\r
-            if (mOAuth2Check.isChecked())\r
-                Toast.makeText(this, R.string.auth_expired_oauth_token_toast, Toast.LENGTH_LONG).show();\r
-            else\r
-                Toast.makeText(this, R.string.auth_expired_basic_auth_toast, Toast.LENGTH_LONG).show();\r
+            if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType)) {\r
+                //Toast.makeText(this, R.string.auth_expired_oauth_token_toast, Toast.LENGTH_LONG).show();\r
+                showAuthMessage(getString(R.string.auth_expired_oauth_token_toast));\r
+            } else if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {\r
+                //Toast.makeText(this, R.string.auth_expired_saml_sso_token_toast, Toast.LENGTH_LONG).show();\r
+                showAuthMessage(getString(R.string.auth_expired_saml_sso_token_toast));\r
+            } else {\r
+                //Toast.makeText(this, R.string.auth_expired_basic_auth_toast, Toast.LENGTH_LONG).show();\r
+                showAuthMessage(getString(R.string.auth_expired_basic_auth_toast));\r
+            }\r
         }\r
 \r
         if (mNewCapturedUriFromOAuth2Redirection != null) {\r
@@ -397,6 +498,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         }\r
 \r
         mJustCreated = false;\r
+        \r
     }\r
 \r
 \r
@@ -418,7 +520,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
                 getString(R.string.oauth2_grant_type),\r
                 queryParameters);\r
         //WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext());\r
-        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mOAuthTokenEndpointText.getText().toString().trim()), getApplicationContext());\r
+        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mOAuthTokenEndpointText.getText().toString().trim()), getApplicationContext(), true);\r
         operation.execute(client, this, mHandler);\r
     }\r
 \r
@@ -482,7 +584,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             mServerStatusIcon = R.drawable.progress_small;\r
             showServerStatus();\r
             mOcServerChkOperation = new  OwnCloudServerCheckOperation(uri, this);\r
-            WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(uri), this);\r
+            WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(uri), this, true);\r
             mOperationThread = mOcServerChkOperation.execute(client, this, mHandler);\r
         } else {\r
             mServerStatusText = 0;\r
@@ -582,9 +684,10 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             return;\r
         }\r
 \r
-        if (mOAuth2Check.isChecked()) {\r
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType)) {\r
             startOauthorization();\r
-\r
+        } else if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) { \r
+            startSamlBasedFederatedSingleSignOnAuthorization();\r
         } else {\r
             checkBasicAuthorization();\r
         }\r
@@ -597,7 +700,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
      */\r
     private void checkBasicAuthorization() {\r
         /// get the path to the root folder through WebDAV from the version server\r
-        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, false);\r
+        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);\r
 \r
         /// get basic credentials entered by user\r
         String username = mUsernameInput.getText().toString();\r
@@ -608,7 +711,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 \r
         /// test credentials accessing the root folder\r
         mAuthCheckOperation = new  ExistenceCheckOperation("", this, false);\r
-        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this);\r
+        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, true);\r
         client.setBasicCredentials(username, password);\r
         mOperationThread = mAuthCheckOperation.execute(client, this, mHandler);\r
     }\r
@@ -623,6 +726,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         mAuthStatusIcon = R.drawable.progress_small;\r
         mAuthStatusText = R.string.oauth_login_connection;\r
         showAuthStatus();\r
+        \r
 \r
         // GET AUTHORIZATION request\r
         //Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));\r
@@ -641,6 +745,27 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 \r
 \r
     /**\r
+     * Starts the Web Single Sign On flow to get access to the root folder\r
+     * in the server.\r
+     */\r
+    private void startSamlBasedFederatedSingleSignOnAuthorization() {\r
+        // be gentle with the user\r
+        mAuthStatusIcon = R.drawable.progress_small;\r
+        mAuthStatusText = R.string.auth_connecting_auth_server;\r
+        showAuthStatus();\r
+        showDialog(DIALOG_LOGIN_PROGRESS);\r
+        \r
+        /// get the path to the root folder through WebDAV from the version server\r
+        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);\r
+\r
+        /// test credentials accessing the root folder\r
+        mAuthCheckOperation = new  ExistenceCheckOperation("", this, false);\r
+        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, false);\r
+        mOperationThread = mAuthCheckOperation.execute(client, this, mHandler);\r
+      \r
+    }\r
+\r
+    /**\r
      * Callback method invoked when a RemoteOperation executed by this Activity finishes.\r
      * \r
      * Dispatches the operation flow to the right method.\r
@@ -655,9 +780,41 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             onGetOAuthAccessTokenFinish((OAuth2GetAccessToken)operation, result);\r
 \r
         } else if (operation instanceof ExistenceCheckOperation)  {\r
-            onAuthorizationCheckFinish((ExistenceCheckOperation)operation, result);\r
-\r
+            if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {\r
+                onSamlBasedFederatedSingleSignOnAuthorizationStart(operation, result);\r
+                \r
+            } else {\r
+                onAuthorizationCheckFinish((ExistenceCheckOperation)operation, result);\r
+            }\r
+        }\r
+    }\r
+    \r
+    \r
+    private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperation operation, RemoteOperationResult result) {\r
+        try {\r
+            dismissDialog(DIALOG_LOGIN_PROGRESS);\r
+        } catch (IllegalArgumentException e) {\r
+            // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens\r
+        }\r
+        
+        //if (result.isTemporalRedirection() && result.isIdPRedirection()) {\r
+        if (result.isIdPRedirection()) {
+            String url = result.getRedirectedLocation();\r
+            String targetUrl = mHostBaseUrl + AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);\r
+            \r
+            // Show dialog\r
+            mSamlDialog = SamlWebViewDialog.newInstance(url, targetUrl);            \r
+            mSamlDialog.show(getSupportFragmentManager(), TAG_SAML_DIALOG);\r
+            \r
+            mAuthStatusIcon = 0;\r
+            mAuthStatusText = 0;\r
+            \r
+        } else {\r
+            mAuthStatusIcon = R.drawable.common_error;\r
+            mAuthStatusText = R.string.auth_unsupported_auth_method;\r
+            \r
         }\r
+        showAuthStatus();\r
     }\r
 \r
 \r
@@ -723,7 +880,6 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             }\r
 \r
         }\r
-        Log_OC.d(TAG, "URL Normalize " + url);\r
         return (url != null ? url : "");\r
     }\r
 \r
@@ -883,6 +1039,12 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         case OAUTH2_ERROR_ACCESS_DENIED:\r
             mAuthStatusText = R.string.auth_oauth_error_access_denied;\r
             break;\r
+        case ACCOUNT_NOT_NEW:\r
+            mAuthStatusText = R.string.auth_account_not_new;\r
+            break;\r
+        case ACCOUNT_NOT_THE_SAME:\r
+            mAuthStatusText = R.string.auth_account_not_the_same;\r
+            break;\r
         case UNHANDLED_HTTP_CODE:\r
         case UNKNOWN_ERROR:\r
             mAuthStatusText = R.string.auth_unknown_error_title;\r
@@ -908,17 +1070,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens\r
         }\r
 \r
-        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, true);\r
+        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);\r
         if (result.isSuccess() && webdav_path != null) {\r
             /// be gentle with the user\r
             showDialog(DIALOG_LOGIN_PROGRESS);\r
 \r
             /// time to test the retrieved access token on the ownCloud server\r
-            mOAuthAccessToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);\r
-            Log_OC.d(TAG, "Got ACCESS TOKEN: " + mOAuthAccessToken);\r
+            mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);\r
+            Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);\r
             mAuthCheckOperation = new ExistenceCheckOperation("", this, false);\r
-            WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this);\r
-            client.setBearerCredentials(mOAuthAccessToken);\r
+            WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, true);\r
+            client.setBearerCredentials(mAuthToken);\r
             mAuthCheckOperation.execute(client, this, mHandler);\r
 \r
         } else {\r
@@ -947,14 +1109,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         if (result.isSuccess()) {\r
             Log_OC.d(TAG, "Successful access - time to save the account");\r
 \r
+            boolean success = false;\r
             if (mAction == ACTION_CREATE) {\r
-                createAccount();\r
+                success = createAccount();\r
 \r
             } else {\r
-                updateToken();\r
+                success = updateToken();\r
             }\r
 \r
-            finish();\r
+            if (success) {\r
+                finish();\r
+            }\r
 \r
         } else if (result.isServerFail() || result.isException()) {\r
             /// if server fail or exception in authorization, the UI is updated as when a server check failed\r
@@ -987,6 +1152,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             showAuthStatus();\r
             Log_OC.d(TAG, "Access failed: " + result.getLogMessage());\r
         }\r
+\r
     }\r
 \r
 \r
@@ -994,20 +1160,39 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
      * Sets the proper response to get that the Account Authenticator that started this activity saves \r
      * a new authorization token for mAccount.\r
      */\r
-    private void updateToken() {\r
+    private boolean updateToken() {\r
         Bundle response = new Bundle();\r
         response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);\r
         response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);\r
-        boolean isOAuth = mOAuth2Check.isChecked();\r
-        if (isOAuth) {\r
-            response.putString(AccountManager.KEY_AUTHTOKEN, mOAuthAccessToken);\r
+        \r
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType)) { \r
+            response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);\r
+            // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention\r
+            mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);\r
+            \r
+        } else if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {\r
+            String username = getUserNameForSamlSso();\r
+            if (!mUsernameInput.getText().toString().equals(username)) {\r
+                // fail - not a new account, but an existing one; disallow\r
+                RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME); \r
+                updateAuthStatusIconAndText(result);\r
+                showAuthStatus();\r
+                Log_OC.d(TAG, result.getLogMessage());\r
+                \r
+                return false;\r
+            }\r
+            \r
+            response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);\r
             // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention\r
-            mAccountMgr.setAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, mOAuthAccessToken);\r
+            mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);\r
+            \r
         } else {\r
             response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());\r
             mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());\r
         }\r
         setAccountAuthenticatorResult(response);\r
+        \r
+        return true;\r
     }\r
 \r
 \r
@@ -1018,13 +1203,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
      * \r
      * TODO Decide how to name the OAuth accounts\r
      */\r
-    private void createAccount() {\r
+    private boolean createAccount() {\r
         /// create and save new ownCloud account\r
-        boolean isOAuth = mOAuth2Check.isChecked();\r
+        boolean isOAuth = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType);\r
+        boolean isSaml =  AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType);\r
 \r
         Uri uri = Uri.parse(mHostBaseUrl);\r
         String username = mUsernameInput.getText().toString().trim();\r
-        if (isOAuth) {\r
+        if (isSaml) {\r
+            username = getUserNameForSamlSso();\r
+            \r
+        } else if (isOAuth) {\r
             username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();\r
         }            \r
         String accountName = username + "@" + uri.getHost();\r
@@ -1032,45 +1221,78 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             accountName += ":" + uri.getPort();\r
         }\r
         mAccount = new Account(accountName, AccountAuthenticator.ACCOUNT_TYPE);\r
-        if (isOAuth) {\r
-            mAccountMgr.addAccountExplicitly(mAccount, "", null);  // with our implementation, the password is never input in the app\r
+        if (AccountUtils.exists(mAccount, getApplicationContext())) {\r
+            // fail - not a new account, but an existing one; disallow\r
+            RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW); \r
+            updateAuthStatusIconAndText(result);\r
+            showAuthStatus();\r
+            Log_OC.d(TAG, result.getLogMessage());\r
+            return false;\r
+            \r
         } else {\r
-            mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);\r
-        }\r
-\r
-        /// add the new account as default in preferences, if there is none already\r
-        Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);\r
-        if (defaultAccount == null) {\r
-            SharedPreferences.Editor editor = PreferenceManager\r
-                    .getDefaultSharedPreferences(this).edit();\r
-            editor.putString("select_oc_account", accountName);\r
-            editor.commit();\r
+        \r
+            if (isOAuth || isSaml) {\r
+                mAccountMgr.addAccountExplicitly(mAccount, "", null);  // with external authorizations, the password is never input in the app\r
+            } else {\r
+                mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);\r
+            }\r
+    \r
+            /// add the new account as default in preferences, if there is none already\r
+            Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);\r
+            if (defaultAccount == null) {\r
+                SharedPreferences.Editor editor = PreferenceManager\r
+                        .getDefaultSharedPreferences(this).edit();\r
+                editor.putString("select_oc_account", accountName);\r
+                editor.commit();\r
+            }\r
+    \r
+            /// prepare result to return to the Authenticator\r
+            //  TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done\r
+            final Intent intent = new Intent();       \r
+            intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,    AccountAuthenticator.ACCOUNT_TYPE);\r
+            intent.putExtra(AccountManager.KEY_ACCOUNT_NAME,    mAccount.name);\r
+            /*if (!isOAuth)\r
+                intent.putExtra(AccountManager.KEY_AUTHTOKEN,   AccountAuthenticator.ACCOUNT_TYPE); */\r
+            intent.putExtra(AccountManager.KEY_USERDATA,        username);\r
+            if (isOAuth || isSaml) {\r
+                mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);\r
+            }\r
+            /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA\r
+            mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION,    mDiscoveredVersion.toString());\r
+            mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL,   mHostBaseUrl);\r
+            if (isSaml) {\r
+                mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE"); \r
+            } else if (isOAuth) {\r
+                mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2, "TRUE");  \r
+            }\r
+    \r
+            setAccountAuthenticatorResult(intent.getExtras());\r
+            setResult(RESULT_OK, intent);\r
+    \r
+            /// immediately request for the synchronization of the new account\r
+            Bundle bundle = new Bundle();\r
+            bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);\r
+            ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);\r
+            syncAccount();\r
+//          Bundle bundle = new Bundle();\r
+//          bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);\r
+//          ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);\r
+            return true;\r
         }\r
+    }\r
 \r
-        /// prepare result to return to the Authenticator\r
-        //  TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done\r
-        final Intent intent = new Intent();       \r
-        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,    AccountAuthenticator.ACCOUNT_TYPE);\r
-        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME,    mAccount.name);\r
-        if (!isOAuth)\r
-            intent.putExtra(AccountManager.KEY_AUTHTOKEN,   AccountAuthenticator.ACCOUNT_TYPE); // TODO check this; not sure it's right; maybe\r
-        intent.putExtra(AccountManager.KEY_USERDATA,        username);\r
-        if (isOAuth) {\r
-            mAccountMgr.setAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, mOAuthAccessToken);\r
+    \r
+    private String getUserNameForSamlSso() {\r
+        if (mAuthToken != null) {\r
+            String [] cookies = mAuthToken.split(";");\r
+            for (int i=0; i<cookies.length; i++) {\r
+                if (cookies[i].startsWith(KEY_OC_USERNAME_EQUALS )) {\r
+                    String value = Uri.decode(cookies[i].substring(KEY_OC_USERNAME_EQUALS.length()));\r
+                    return value;\r
+                }\r
+            }\r
         }\r
-        /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA\r
-        mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION,    mDiscoveredVersion.toString());\r
-        mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL,   mHostBaseUrl);\r
-        if (isOAuth)\r
-            mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2, "TRUE");  // TODO this flag should be unnecessary\r
-\r
-        setAccountAuthenticatorResult(intent.getExtras());\r
-        setResult(RESULT_OK, intent);\r
-\r
-        /// immediately request for the synchronization of the new account\r
-        Bundle bundle = new Bundle();\r
-        bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);\r
-        ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);\r
+        return "";\r
     }\r
 \r
 \r
@@ -1259,33 +1481,43 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
      * @param view      'View password' 'button'\r
      */\r
     public void onCheckClick(View view) {\r
-        CheckBox oAuth2Check = (CheckBox)view;      \r
-        changeViewByOAuth2Check(oAuth2Check.isChecked());\r
-\r
+        CheckBox oAuth2Check = (CheckBox)view;\r
+        if (oAuth2Check.isChecked()) {\r
+            mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN;\r
+        } else {\r
+            mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;\r
+        }\r
+        adaptViewAccordingToAuthenticationMethod();\r
     }\r
 \r
+    \r
     /**\r
-     * Changes the visibility of input elements depending upon the kind of authorization\r
-     * chosen by the user: basic or OAuth\r
-     * \r
-     * @param checked       'True' when OAuth is selected.\r
+     * Changes the visibility of input elements depending on\r
+     * the current authorization method.\r
      */\r
-    public void changeViewByOAuth2Check(Boolean checked) {\r
-\r
-        if (checked) {\r
+    private void adaptViewAccordingToAuthenticationMethod () {\r
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType)) {\r
+            // OAuth 2 authorization\r
             mOAuthAuthEndpointText.setVisibility(View.VISIBLE);\r
             mOAuthTokenEndpointText.setVisibility(View.VISIBLE);\r
             mUsernameInput.setVisibility(View.GONE);\r
             mPasswordInput.setVisibility(View.GONE);\r
+            \r
+        } else if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {\r
+            // SAML-based web Single Sign On\r
+            mOAuthAuthEndpointText.setVisibility(View.GONE);\r
+            mOAuthTokenEndpointText.setVisibility(View.GONE);\r
+            mUsernameInput.setVisibility(View.GONE);\r
+            mPasswordInput.setVisibility(View.GONE);\r
         } else {\r
+            // basic HTTP authorization\r
             mOAuthAuthEndpointText.setVisibility(View.GONE);\r
             mOAuthTokenEndpointText.setVisibility(View.GONE);\r
             mUsernameInput.setVisibility(View.VISIBLE);\r
             mPasswordInput.setVisibility(View.VISIBLE);\r
-        }     \r
-\r
-    }    \r
-\r
+        }\r
+    }\r
+    \r
     /**\r
      * Called from SslValidatorDialog when a new server certificate was correctly saved.\r
      */\r
@@ -1306,15 +1538,20 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     /**\r
      *  Called when the 'action' button in an IME is pressed ('enter' in software keyboard).\r
      * \r
-     *  Used to trigger the authorization check when the user presses 'enter' after writing the password.\r
+     *  Used to trigger the authentication check when the user presses 'enter' after writing the password, \r
+     *  or to throw the server test when the only field on screen is the URL input field.\r
      */\r
     @Override\r
     public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {\r
-        if (inputField != null && inputField.equals(mPasswordInput) && \r
-                actionId == EditorInfo.IME_ACTION_DONE) {\r
+        if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null && inputField.equals(mPasswordInput)) {\r
             if (mOkButton.isEnabled()) {\r
                 mOkButton.performClick();\r
             }\r
+            \r
+        } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null && inputField.equals(mHostUrlInput)) {\r
+            if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {\r
+                checkOcServer();\r
+            }\r
         }\r
         return false;   // always return false to grant that the software keyboard is hidden anyway\r
     }\r
@@ -1352,4 +1589,76 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         public abstract boolean onDrawableTouch(final MotionEvent event);\r
     }\r
 \r
+\r
+    public void onSamlDialogSuccess(String sessionCookie){\r
+        mAuthToken = sessionCookie;\r
+        \r
+        if (sessionCookie != null && sessionCookie.length() > 0) {\r
+            mAuthToken = sessionCookie;\r
+            boolean success = false;\r
+            if (mAction == ACTION_CREATE) {\r
+                success = createAccount();\r
+        \r
+            } else {\r
+                success = updateToken();\r
+            }\r
+            if (success) {\r
+                finish();\r
+            }\r
+        }\r
+\r
+            \r
+    }\r
+\r
+\r
+    @Override\r
+    public void onSsoFinished(String sessionCookies) {\r
+        //Toast.makeText(this, "got cookies: " + sessionCookie, Toast.LENGTH_LONG).show();\r
+\r
+        if (sessionCookies != null && sessionCookies.length() > 0) {\r
+            Log_OC.d(TAG, "Successful SSO - time to save the account");\r
+            onSamlDialogSuccess(sessionCookies);\r
+            Fragment fd = getSupportFragmentManager().findFragmentByTag(TAG_SAML_DIALOG);\r
+            if (fd != null && fd instanceof SherlockDialogFragment) {\r
+                Dialog d = ((SherlockDialogFragment)fd).getDialog();\r
+                if (d != null && d.isShowing()) {\r
+                    d.dismiss();\r
+                }\r
+            }\r
+\r
+        } else { \r
+            // TODO - show fail\r
+            Log_OC.d(TAG, "SSO failed");\r
+        }\r
+    \r
+    }\r
+    \r
+    /** Show auth_message \r
+     * \r
+     * @param message\r
+     */\r
+    private void showAuthMessage(String message) {\r
+       mAuthMessage.setVisibility(View.VISIBLE);\r
+       mAuthMessage.setText(message);\r
+    }\r
+    \r
+    private void hideAuthMessage() {\r
+        mAuthMessage.setVisibility(View.GONE);\r
+    }\r
+\r
+    private void syncAccount(){\r
+        /// immediately request for the synchronization of the new account\r
+        Bundle bundle = new Bundle();\r
+        bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);\r
+        ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);\r
+    }\r
+    \r
+    @Override\r
+    public boolean onTouchEvent(MotionEvent event) {\r
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType) &&\r
+                mHostUrlInput.hasFocus() && event.getAction() == MotionEvent.ACTION_DOWN) {\r
+            checkOcServer();\r
+        }\r
+        return super.onTouchEvent(event);\r
+    }\r
 }\r
diff --git a/src/com/owncloud/android/authentication/SsoWebViewClient.java b/src/com/owncloud/android/authentication/SsoWebViewClient.java
new file mode 100644 (file)
index 0000000..4f26a80
--- /dev/null
@@ -0,0 +1,175 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013 ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License version 2,
+ *   as published by the Free Software Foundation.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.authentication;
+
+import java.lang.ref.WeakReference;
+
+import com.owncloud.android.Log_OC;
+
+import android.graphics.Bitmap;
+import android.os.Handler;
+import android.os.Message;
+import android.view.View;
+import android.webkit.CookieManager;
+import android.webkit.WebView;
+import android.webkit.WebViewClient;
+
+
+/**
+ * Custom {@link WebViewClient} client aimed to catch the end of a single-sign-on process 
+ * running in the {@link WebView} that is attached to.
+ * 
+ * Assumes that the single-sign-on is kept thanks to a cookie set at the end of the
+ * authentication process.
+ *   
+ * @author David A. Velasco
+ */
+public class SsoWebViewClient extends WebViewClient {
+        
+    private static final String TAG = SsoWebViewClient.class.getSimpleName();
+    
+    public interface SsoWebViewClientListener {
+        public void onSsoFinished(String sessionCookie);
+    }
+    
+    private Handler mListenerHandler;
+    private WeakReference<SsoWebViewClientListener> mListenerRef;
+    private String mTargetUrl;
+    private String mLastReloadedUrlAtError;
+    
+    public SsoWebViewClient (Handler listenerHandler, SsoWebViewClientListener listener) {
+        mListenerHandler = listenerHandler;
+        mListenerRef = new WeakReference<SsoWebViewClient.SsoWebViewClientListener>(listener);
+        mTargetUrl = "fake://url.to.be.set";
+        mLastReloadedUrlAtError = null;
+    }
+    
+    public String getTargetUrl() {
+        return mTargetUrl;
+    }
+    
+    public void setTargetUrl(String targetUrl) {
+        mTargetUrl = targetUrl;
+    }
+
+    @Override
+    public void onPageStarted (WebView view, String url, Bitmap favicon) {
+        Log_OC.d(TAG, "onPageStarted : " + url);
+        super.onPageStarted(view, url, favicon);
+    }
+    
+    @Override
+    public void onFormResubmission (WebView view, Message dontResend, Message resend) {
+        Log_OC.d(TAG, "onFormResubMission ");
+
+        // necessary to grant reload of last page when device orientation is changed after sending a form
+        resend.sendToTarget();
+    }
+
+    @Override
+    public boolean shouldOverrideUrlLoading(WebView view, String url) {
+        return false;
+    }
+    
+    @Override
+    public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) {
+        Log_OC.e(TAG, "onReceivedError : " + failingUrl + ", code " + errorCode + ", description: " + description);
+        if (!failingUrl.equals(mLastReloadedUrlAtError)) {
+            view.reload();
+            mLastReloadedUrlAtError = failingUrl;
+        } else {
+            mLastReloadedUrlAtError = null;
+            super.onReceivedError(view, errorCode, description, failingUrl);
+        }
+    }
+    
+    @Override
+    public void onPageFinished (WebView view, String url) {
+        Log_OC.d(TAG, "onPageFinished : " + url);
+        mLastReloadedUrlAtError = null;
+        if (url.startsWith(mTargetUrl)) {
+            view.setVisibility(View.GONE);
+            CookieManager cookieManager = CookieManager.getInstance();
+            final String cookies = cookieManager.getCookie(url);
+            //Log_OC.d(TAG, "Cookies: " + cookies);
+            if (mListenerHandler != null && mListenerRef != null) {
+                // this is good idea because onPageFinished is not running in the UI thread
+                mListenerHandler.post(new Runnable() {
+                    @Override
+                    public void run() {
+                        SsoWebViewClientListener listener = mListenerRef.get();
+                        if (listener != null) {
+                            listener.onSsoFinished(cookies);
+                        }
+                    }
+                });
+            }
+        }
+
+    }
+    
+    /*
+    @Override
+    public void doUpdateVisitedHistory (WebView view, String url, boolean isReload) {
+        Log_OC.d(TAG, "doUpdateVisitedHistory : " + url);
+    }
+    
+    @Override
+    public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
+        Log_OC.d(TAG, "onReceivedSslError : " + error);
+    }
+    
+    @Override
+    public void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm) {
+        Log_OC.d(TAG, "onReceivedHttpAuthRequest : " + host);
+    }
+
+    @Override
+    public WebResourceResponse shouldInterceptRequest (WebView view, String url) {
+        Log_OC.d(TAG, "shouldInterceptRequest : " + url);
+        return null;
+    }
+    
+    @Override
+    public void onLoadResource (WebView view, String url) {
+        Log_OC.d(TAG, "onLoadResource : " + url);   
+    }
+    
+    @Override
+    public void onReceivedLoginRequest (WebView view, String realm, String account, String args) {
+        Log_OC.d(TAG, "onReceivedLoginRequest : " + realm + ", " + account + ", " + args);
+    }
+    
+    @Override
+    public void onScaleChanged (WebView view, float oldScale, float newScale) {
+        Log_OC.d(TAG, "onScaleChanged : " + oldScale + " -> " + newScale);
+        super.onScaleChanged(view, oldScale, newScale);
+    }
+
+    @Override
+    public void onUnhandledKeyEvent (WebView view, KeyEvent event) {
+        Log_OC.d(TAG, "onUnhandledKeyEvent : " + event);
+    }
+    
+    @Override
+    public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
+        Log_OC.d(TAG, "shouldOverrideKeyEvent : " + event);
+        return false;
+    }
+    */
+}
index f9b2576..4825b7b 100644 (file)
@@ -561,16 +561,16 @@ public class FileDataStorageManager implements DataStorageManager {
                 try {
                     c = getContentProvider().query(ProviderTableMeta.CONTENT_URI, 
                             null,
-                            ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ?",
-                            new String[] { mAccount.name, dir.getRemotePath() + "%" }, null);
+                            ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ? ",
+                            new String[] { mAccount.name, dir.getRemotePath() + "%"  }, ProviderTableMeta.FILE_PATH + " ASC ");
                 } catch (RemoteException e) {
                     Log_OC.e(TAG, e.getMessage());
                 }
             } else {
                 c = getContentResolver().query(ProviderTableMeta.CONTENT_URI, 
                         null,
-                        ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ?",
-                        new String[] { mAccount.name, dir.getRemotePath() + "%" }, null);
+                        ProviderTableMeta.FILE_ACCOUNT_OWNER + "=? AND " + ProviderTableMeta.FILE_PATH + " LIKE ? ",
+                        new String[] { mAccount.name, dir.getRemotePath() + "%"  }, ProviderTableMeta.FILE_PATH + " ASC ");
             }
 
             /// 2. prepare a batch of update operations to change all the descendants
index 02a8a45..e07a17b 100644 (file)
@@ -28,6 +28,7 @@ import java.util.Vector;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 
+import com.owncloud.android.authentication.AccountAuthenticator;
 import com.owncloud.android.authentication.AuthenticatorActivity;
 import com.owncloud.android.datamodel.FileDataStorageManager;
 import com.owncloud.android.datamodel.OCFile;
@@ -463,7 +464,10 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
             int contentId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;
             Notification finalNotification = new Notification(R.drawable.icon, getString(tickerId), System.currentTimeMillis());
             finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
-            boolean needsToUpdateCredentials = (downloadResult.getCode() == ResultCode.UNAUTHORIZED);
+            boolean needsToUpdateCredentials = (downloadResult.getCode() == ResultCode.UNAUTHORIZED ||
+                                                // (downloadResult.isTemporalRedirection() && downloadResult.isIdPRedirection()
+                                                  (downloadResult.isIdPRedirection()
+                                                        && AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mDownloadClient.getAuthTokenType())));
             if (needsToUpdateCredentials) {
                 // let the user update credentials with one click
                 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
index e9f445a..a02e74a 100644 (file)
@@ -579,7 +579,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
                 mUploadClient.exhaustResponse(propfind.getResponseBodyAsStream());
             }
 
-            result = new RemoteOperationResult(isMultiStatus, status);
+            result = new RemoteOperationResult(isMultiStatus, status, propfind.getResponseHeaders());
             Log_OC.i(TAG, "Update: synchronizing properties for uploaded " + mCurrentUpload.getRemotePath() + ": "
                     + result.getLogMessage());
 
@@ -791,7 +791,13 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
             Notification finalNotification = new Notification(R.drawable.icon,
                     getString(R.string.uploader_upload_failed_ticker), System.currentTimeMillis());
             finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
-            if (uploadResult.getCode() == ResultCode.UNAUTHORIZED) {
+            String content = null;
+            
+            boolean needsToUpdateCredentials = (uploadResult.getCode() == ResultCode.UNAUTHORIZED ||
+                    //(uploadResult.isTemporalRedirection() && uploadResult.isIdPRedirection() && 
+                    (uploadResult.isIdPRedirection() &&
+                            AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mUploadClient.getAuthTokenType())));
+            if (needsToUpdateCredentials) {
                 // let the user update credentials with one click
                 Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
                 updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, upload.getAccount());
@@ -801,62 +807,65 @@ public class FileUploader extends Service implements OnDatatransferProgressListe
                 updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                 updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
                 finalNotification.contentIntent = PendingIntent.getActivity(this, (int)System.currentTimeMillis(), updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT);
+                content =  String.format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
+                finalNotification.setLatestEventInfo(getApplicationContext(),
+                        getString(R.string.uploader_upload_failed_ticker), content, finalNotification.contentIntent);
                 mUploadClient = null;   // grant that future retries on the same account will get the fresh credentials
             } else {
                 // TODO put something smart in the contentIntent below
-                finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
-            }
+            //    finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
+            //}
             
-            String content = null;
-            if (uploadResult.getCode() == ResultCode.LOCAL_STORAGE_FULL
-                    || uploadResult.getCode() == ResultCode.LOCAL_STORAGE_NOT_COPIED) {
-                // TODO we need a class to provide error messages for the users
-                // from a RemoteOperationResult and a RemoteOperation
-                content = String.format(getString(R.string.error__upload__local_file_not_copied), upload.getFileName(),
-                        getString(R.string.app_name));
-            } else if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
-                content = getString(R.string.failed_upload_quota_exceeded_text);
-            } else {
-                content = String
-                        .format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
-            }
+                if (uploadResult.getCode() == ResultCode.LOCAL_STORAGE_FULL
+                        || uploadResult.getCode() == ResultCode.LOCAL_STORAGE_NOT_COPIED) {
+                    // TODO we need a class to provide error messages for the users
+                    // from a RemoteOperationResult and a RemoteOperation
+                    content = String.format(getString(R.string.error__upload__local_file_not_copied), upload.getFileName(),
+                            getString(R.string.app_name));
+                } else if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
+                    content = getString(R.string.failed_upload_quota_exceeded_text);
+                } else {
+                    content = String
+                            .format(getString(R.string.uploader_upload_failed_content_single), upload.getFileName());
+                }
 
-            // we add only for instant-uploads the InstantUploadActivity and the
-            // db entry
-            Intent detailUploadIntent = null;
-            if (upload.isInstant() && InstantUploadActivity.IS_ENABLED) {
-                detailUploadIntent = new Intent(this, InstantUploadActivity.class);
-                detailUploadIntent.putExtra(FileUploader.KEY_ACCOUNT, upload.getAccount());
-            } else {
-                detailUploadIntent = new Intent(this, FailedUploadActivity.class);
-                detailUploadIntent.putExtra(FailedUploadActivity.MESSAGE, content);
-            }
-            finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
-                    (int) System.currentTimeMillis(), detailUploadIntent, PendingIntent.FLAG_UPDATE_CURRENT
-                            | PendingIntent.FLAG_ONE_SHOT);
-
-            if (upload.isInstant()) {
-                DbHandler db = null;
-                try {
-                    db = new DbHandler(this.getBaseContext());
-                    String message = uploadResult.getLogMessage() + " errorCode: " + uploadResult.getCode();
-                    Log_OC.e(TAG, message + " Http-Code: " + uploadResult.getHttpCode());
-                    if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
-                        message = getString(R.string.failed_upload_quota_exceeded_text);
-                    }
-                    if (db.updateFileState(upload.getOriginalStoragePath(), DbHandler.UPLOAD_STATUS_UPLOAD_FAILED,
-                            message) == 0) {
-                        db.putFileForLater(upload.getOriginalStoragePath(), upload.getAccount().name, message);
-                    }
-                } finally {
-                    if (db != null) {
-                        db.close();
+                // we add only for instant-uploads the InstantUploadActivity and the
+                // db entry
+                Intent detailUploadIntent = null;
+                if (upload.isInstant() && InstantUploadActivity.IS_ENABLED) {
+                    detailUploadIntent = new Intent(this, InstantUploadActivity.class);
+                    detailUploadIntent.putExtra(FileUploader.KEY_ACCOUNT, upload.getAccount());
+                } else {
+                    detailUploadIntent = new Intent(this, FailedUploadActivity.class);
+                    detailUploadIntent.putExtra(FailedUploadActivity.MESSAGE, content);
+                }
+                finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(),
+                        (int) System.currentTimeMillis(), detailUploadIntent, PendingIntent.FLAG_UPDATE_CURRENT
+                        | PendingIntent.FLAG_ONE_SHOT);
+
+                if (upload.isInstant()) {
+                    DbHandler db = null;
+                    try {
+                        db = new DbHandler(this.getBaseContext());
+                        String message = uploadResult.getLogMessage() + " errorCode: " + uploadResult.getCode();
+                        Log_OC.e(TAG, message + " Http-Code: " + uploadResult.getHttpCode());
+                        if (uploadResult.getCode() == ResultCode.QUOTA_EXCEEDED) {
+                            message = getString(R.string.failed_upload_quota_exceeded_text);
+                        }
+                        if (db.updateFileState(upload.getOriginalStoragePath(), DbHandler.UPLOAD_STATUS_UPLOAD_FAILED,
+                                message) == 0) {
+                            db.putFileForLater(upload.getOriginalStoragePath(), upload.getAccount().name, message);
+                        }
+                    } finally {
+                        if (db != null) {
+                            db.close();
+                        }
                     }
                 }
             }
             finalNotification.setLatestEventInfo(getApplicationContext(),
                     getString(R.string.uploader_upload_failed_ticker), content, finalNotification.contentIntent);
-
+            
             mNotificationManager.notify(R.string.uploader_upload_failed_ticker, finalNotification);
         }
 
index 04fb7ac..75aed4a 100644 (file)
@@ -32,6 +32,7 @@ import javax.net.ssl.SSLContext;
 import javax.net.ssl.TrustManager;
 
 import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
+import org.apache.commons.httpclient.methods.GetMethod;
 import org.apache.commons.httpclient.protocol.Protocol;
 import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier;
 import org.apache.http.conn.ssl.X509HostnameVerifier;
@@ -90,12 +91,18 @@ public class OwnCloudClientUtils {
         //Log_OC.d(TAG, "Creating WebdavClient associated to " + account.name);
        
         Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account));
-        WebdavClient client = createOwnCloudClient(uri, appContext);
         AccountManager am = AccountManager.get(appContext);
-        if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null) {    // TODO avoid a call to getUserData here
+        boolean isOauth2 = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null;   // TODO avoid calling to getUserData here
+        boolean isSamlSso = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null;
+        WebdavClient client = createOwnCloudClient(uri, appContext, !isSamlSso);
+        if (isOauth2) {    
             String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, false);
             client.setBearerCredentials(accessToken);   // TODO not assume that the access token is a bearer token
         
+        } else if (isSamlSso) {    // TODO avoid a call to getUserData here
+            String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE, false);
+            client.setSsoSessionCookie(accessToken);
+            
         } else {
             String username = account.name.substring(0, account.name.lastIndexOf('@'));
             //String password = am.getPassword(account);
@@ -109,16 +116,25 @@ public class OwnCloudClientUtils {
     
     public static WebdavClient createOwnCloudClient (Account account, Context appContext, Activity currentActivity) throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException {
         Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account));
-        WebdavClient client = createOwnCloudClient(uri, appContext);
         AccountManager am = AccountManager.get(appContext);
-        if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null) {    // TODO avoid a call to getUserData here
+        boolean isOauth2 = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null;   // TODO avoid calling to getUserData here
+        boolean isSamlSso = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null;
+        WebdavClient client = createOwnCloudClient(uri, appContext, !isSamlSso);
+        
+        if (isOauth2) {    // TODO avoid a call to getUserData here
             AccountManagerFuture<Bundle> future =  am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, null, currentActivity, null, null);
             Bundle result = future.getResult();
             String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN);
-            //String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, false);
             if (accessToken == null) throw new AuthenticatorException("WTF!");
             client.setBearerCredentials(accessToken);   // TODO not assume that the access token is a bearer token
-            
+
+        } else if (isSamlSso) {    // TODO avoid a call to getUserData here
+            AccountManagerFuture<Bundle> future =  am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE, null, currentActivity, null, null);
+            Bundle result = future.getResult();
+            String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN);
+            if (accessToken == null) throw new AuthenticatorException("WTF!");
+            client.setSsoSessionCookie(accessToken);
+
         } else {
             String username = account.name.substring(0, account.name.lastIndexOf('@'));
             //String password = am.getPassword(account);
@@ -139,10 +155,7 @@ public class OwnCloudClientUtils {
      * @param context   Android context where the WebdavClient is being created.
      * @return          A WebdavClient object ready to be used
      */
-    public static WebdavClient createOwnCloudClient(Uri uri, Context context) {
-        //Log_OC.d(TAG, "Creating WebdavClient for " + uri);
-        
-        //allowSelfsignedCertificates(true);
+    public static WebdavClient createOwnCloudClient(Uri uri, Context context, boolean followRedirects) {
         try {
             registerAdvancedSslContext(true, context);
         }  catch (GeneralSecurityException e) {
@@ -156,6 +169,7 @@ public class OwnCloudClientUtils {
         
         client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
         client.setBaseUri(uri);
+        client.setFollowRedirects(followRedirects);
         
         return client;
     }
index 697c154..02e1ad0 100644 (file)
@@ -68,6 +68,9 @@ public class ChunkedUploadFileOperation extends UploadFileOperation {
             String uriPrefix = client.getBaseUri() + WebdavUtils.encodePath(getRemotePath()) + "-chunking-" + Math.abs((new Random()).nextInt(9000)+1000) + "-" ;
             long chunkCount = (long) Math.ceil((double)file.length() / CHUNK_SIZE);
             for (int chunkIndex = 0; chunkIndex < chunkCount ; chunkIndex++, offset += CHUNK_SIZE) {
+                if (mPutMethod != null) {
+                    mPutMethod.releaseConnection();    // let the connection available for other methods
+                }
                 mPutMethod = new PutMethod(uriPrefix + chunkCount + "-" + chunkIndex);
                 mPutMethod.addRequestHeader(OC_CHUNKED_HEADER, OC_CHUNKED_HEADER);
                 ((ChunkFromFileChannelRequestEntity)mEntity).setOffset(offset);
index 03c6868..1a38cdb 100644 (file)
@@ -77,7 +77,7 @@ public class CreateFolderOperation extends RemoteOperation {
                 mStorageManager.saveFile(newDir);
             }
 
-            result = new RemoteOperationResult(mkcol.succeeded(), status);
+            result = new RemoteOperationResult(mkcol.succeeded(), status, mkcol.getResponseHeaders());
             Log_OC.d(TAG, "Create directory " + mRemotePath + ": " + result.getLogMessage());
             client.exhaustResponse(mkcol.getResponseBodyAsStream());
                 
index 5745b97..02098b8 100644 (file)
@@ -58,6 +58,7 @@ public class DownloadFileOperation extends RemoteOperation {
     private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
     private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
     private long mModificationTimestamp = 0;
+    private GetMethod mGet;
 
     
     public DownloadFileOperation(Account account, OCFile file) {
@@ -154,7 +155,7 @@ public class DownloadFileOperation extends RemoteOperation {
             if (!moved)
                 result = new RemoteOperationResult(RemoteOperationResult.ResultCode.LOCAL_STORAGE_NOT_MOVED);
             else
-                result = new RemoteOperationResult(isSuccess(status), status);
+                result = new RemoteOperationResult(isSuccess(status), status, (mGet != null ? mGet.getResponseHeaders() : null));
             Log_OC.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage());
             
         } catch (Exception e) {
@@ -174,15 +175,15 @@ public class DownloadFileOperation extends RemoteOperation {
     protected int downloadFile(WebdavClient client, File targetFile) throws HttpException, IOException, OperationCancelledException {
         int status = -1;
         boolean savedFile = false;
-        GetMethod get = new GetMethod(client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()));
+        mGet = new GetMethod(client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()));
         Iterator<OnDatatransferProgressListener> it = null;
         
         FileOutputStream fos = null;
         try {
-            status = client.executeMethod(get);
+            status = client.executeMethod(mGet);
             if (isSuccess(status)) {
                 targetFile.createNewFile();
-                BufferedInputStream bis = new BufferedInputStream(get.getResponseBodyAsStream());
+                BufferedInputStream bis = new BufferedInputStream(mGet.getResponseBodyAsStream());
                 fos = new FileOutputStream(targetFile);
                 long transferred = 0;
 
@@ -191,7 +192,7 @@ public class DownloadFileOperation extends RemoteOperation {
                 while ((readResult = bis.read(bytes)) != -1) {
                     synchronized(mCancellationRequested) {
                         if (mCancellationRequested.get()) {
-                            get.abort();
+                            mGet.abort();
                             throw new OperationCancelledException();
                         }
                     }
@@ -205,14 +206,14 @@ public class DownloadFileOperation extends RemoteOperation {
                     }
                 }
                 savedFile = true;
-                Header modificationTime = get.getResponseHeader("Last-Modified");
+                Header modificationTime = mGet.getResponseHeader("Last-Modified");
                 if (modificationTime != null) {
                     Date d = WebdavUtils.parseResponseDate((String) modificationTime.getValue());
                     mModificationTimestamp = (d != null) ? d.getTime() : 0;
                 }
                 
             } else {
-                client.exhaustResponse(get.getResponseBodyAsStream());
+                client.exhaustResponse(mGet.getResponseBodyAsStream());
             }
                 
         } finally {
@@ -220,7 +221,7 @@ public class DownloadFileOperation extends RemoteOperation {
             if (!savedFile && targetFile.exists()) {
                 targetFile.delete();
             }
-            get.releaseConnection();    // let the connection available for other methods
+            mGet.releaseConnection();    // let the connection available for other methods
         }
         return status;
     }
index 1093986..e404a6f 100644 (file)
@@ -69,7 +69,7 @@ public class ExistenceCheckOperation extends RemoteOperation {
             int status = client.executeMethod(head, TIMEOUT, TIMEOUT);
             client.exhaustResponse(head.getResponseBodyAsStream());
             boolean success = (status == HttpStatus.SC_OK && !mSuccessIfAbsent) || (status == HttpStatus.SC_NOT_FOUND && mSuccessIfAbsent);
-            result = new RemoteOperationResult(success, status);
+            result = new RemoteOperationResult(success, status, head.getResponseHeaders());
             Log_OC.d(TAG, "Existence check for " + client.getBaseUri() + mPath + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ") + "finished with HTTP status " + status + (!success?"(FAIL)":""));
             
         } catch (Exception e) {
index 6d43caf..5d46804 100644 (file)
@@ -80,12 +80,12 @@ public class OAuth2GetAccessToken extends RemoteOperation {
                         result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR);
                     
                     } else {
-                        result = new RemoteOperationResult(true, status);
+                        result = new RemoteOperationResult(true, status, postMethod.getResponseHeaders());
                     }
                     
                 } else {
                     client.exhaustResponse(postMethod.getResponseBodyAsStream());
-                    result = new RemoteOperationResult(false, status);
+                    result = new RemoteOperationResult(false, status, postMethod.getResponseHeaders());
                 }
             }
             
index 4982c66..d95b305 100644 (file)
@@ -80,7 +80,7 @@ public class OwnCloudServerCheckOperation extends RemoteOperation {
                 }
                 
             } else {
-                mLatestResult = new RemoteOperationResult(false, status);
+                mLatestResult = new RemoteOperationResult(false, status, get.getResponseHeaders());
             }
 
         } catch (JSONException e) {
index 711a72b..4d7bcee 100644 (file)
@@ -242,18 +242,28 @@ public abstract class RemoteOperation implements Runnable {
                 result = run(mClient);
         
             repeat = false;
-            if (mCallerActivity != null && mAccount != null && mContext != null && !result.isSuccess() && result.getCode() == ResultCode.UNAUTHORIZED) {
-                /// fail due to lack of authorization in an operation performed in foreground
-                AccountManager am = AccountManager.get(mContext);
+            if (mCallerActivity != null && mAccount != null && mContext != null && !result.isSuccess() &&
+//                    (result.getCode() == ResultCode.UNAUTHORIZED || (result.isTemporalRedirection() && result.isIdPRedirection()))) {
+                    (result.getCode() == ResultCode.UNAUTHORIZED || result.isIdPRedirection())) {
+                /// possible fail due to lack of authorization in an operation performed in foreground
                 Credentials cred = mClient.getCredentials();
-                if (cred instanceof BearerCredentials) {
-                    am.invalidateAuthToken(AccountAuthenticator.ACCOUNT_TYPE, ((BearerCredentials)cred).getAccessToken());
-                } else {
-                    am.clearPassword(mAccount);
+                String ssoSessionCookie = mClient.getSsoSessionCookie();
+                if (cred != null || ssoSessionCookie != null) {
+                    /// confirmed : unauthorized operation
+                    AccountManager am = AccountManager.get(mContext);
+                    boolean bearerAuthorization = (cred != null && cred instanceof BearerCredentials);
+                    boolean samlBasedSsoAuthorization = (cred == null && ssoSessionCookie != null);
+                    if (bearerAuthorization) {
+                        am.invalidateAuthToken(AccountAuthenticator.ACCOUNT_TYPE, ((BearerCredentials)cred).getAccessToken());
+                    } else if (samlBasedSsoAuthorization ) {
+                        am.invalidateAuthToken(AccountAuthenticator.ACCOUNT_TYPE, ssoSessionCookie);
+                    } else {
+                        am.clearPassword(mAccount);
+                    }
+                    mClient = null;
+                    repeat = true;  // when repeated, the creation of a new OwnCloudClient after erasing the saved credentials will trigger the login activity
+                    result = null;
                 }
-                mClient = null;
-                repeat = true;  // when repeated, the creation of a new OwnCloudClient after erasing the saved credentials will trigger the login activity
-                result = null;
             }
         } while (repeat);
         
@@ -278,4 +288,5 @@ public abstract class RemoteOperation implements Runnable {
         return mClient;
     }
 
+
 }
index 6b50f91..ca88210 100644 (file)
@@ -28,6 +28,7 @@ import java.net.UnknownHostException;
 import javax.net.ssl.SSLException;
 
 import org.apache.commons.httpclient.ConnectTimeoutException;
+import org.apache.commons.httpclient.Header;
 import org.apache.commons.httpclient.HttpException;
 import org.apache.commons.httpclient.HttpStatus;
 import org.apache.jackrabbit.webdav.DavException;
@@ -50,7 +51,7 @@ import com.owncloud.android.network.CertificateCombinedException;
 public class RemoteOperationResult implements Serializable {
 
     /** Generated - should be refreshed every time the class changes!! */
-    private static final long serialVersionUID = 6106167714625712390L;
+    private static final long serialVersionUID = -4415103901492836870L;
 
     
     private static final String TAG = "RemoteOperationResult";
@@ -85,20 +86,23 @@ public class RemoteOperationResult implements Serializable {
         OAUTH2_ERROR_ACCESS_DENIED,
         QUOTA_EXCEEDED, 
         ACCOUNT_NOT_FOUND, 
-        ACCOUNT_EXCEPTION
+        ACCOUNT_EXCEPTION, 
+        ACCOUNT_NOT_NEW, 
+        ACCOUNT_NOT_THE_SAME
     }
 
     private boolean mSuccess = false;
     private int mHttpCode = -1;
     private Exception mException = null;
     private ResultCode mCode = ResultCode.UNKNOWN_ERROR;
+    private String mRedirectedLocation;
 
     public RemoteOperationResult(ResultCode code) {
         mCode = code;
         mSuccess = (code == ResultCode.OK || code == ResultCode.OK_SSL || code == ResultCode.OK_NO_SSL || code == ResultCode.OK_NO_CHANGES_ON_DIR);
     }
 
-    public RemoteOperationResult(boolean success, int httpCode) {
+    private RemoteOperationResult(boolean success, int httpCode) {
         mSuccess = success;
         mHttpCode = httpCode;
 
@@ -124,10 +128,24 @@ public class RemoteOperationResult implements Serializable {
                 break;
             default:
                 mCode = ResultCode.UNHANDLED_HTTP_CODE;
-                Log_OC.d(TAG, "RemoteOperationResult has prcessed UNHANDLED_HTTP_CODE: " + httpCode);
+                Log_OC.d(TAG, "RemoteOperationResult has processed UNHANDLED_HTTP_CODE: " + httpCode);
             }
         }
     }
+    
+    public RemoteOperationResult(boolean success, int httpCode, Header[] headers) {
+        this(success, httpCode);
+        if (headers != null) {
+            Header current;
+            for (int i=0; i<headers.length; i++) {
+                current = headers[i];
+                if ("Location".equals(current.getName())) {
+                    mRedirectedLocation = current.getValue();
+                    break;
+                }
+            }
+        }
+    }    
 
     public RemoteOperationResult(Exception e) {
         mException = e;
@@ -282,6 +300,12 @@ public class RemoteOperationResult implements Serializable {
 
         } else if (mCode == ResultCode.LOCAL_STORAGE_NOT_MOVED) {
             return "Error while moving file to final directory";
+
+        } else if (mCode == ResultCode.ACCOUNT_NOT_NEW) {
+            return "Account already existing when creating a new one";
+
+        } else if (mCode == ResultCode.ACCOUNT_NOT_THE_SAME) {
+            return "Authenticated with a different account than the one updating";
         }
 
         return "Operation finished with HTTP status code " + mHttpCode + " (" + (isSuccess() ? "success" : "fail") + ")";
@@ -296,4 +320,18 @@ public class RemoteOperationResult implements Serializable {
         return (mException != null);
     }
 
+    public boolean isTemporalRedirection() {
+        return (mHttpCode == 302 || mHttpCode == 307);
+    }
+
+    public String getRedirectedLocation() {
+        return mRedirectedLocation;
+    }
+    
+    public boolean isIdPRedirection() {
+        return (mRedirectedLocation != null &&
+                (mRedirectedLocation.toUpperCase().contains("SAML") || 
+                mRedirectedLocation.toLowerCase().contains("wayf")));
+    }
+
 }
index 8348b72..9dabfaf 100644 (file)
@@ -88,7 +88,7 @@ public class RemoveFileOperation extends RemoteOperation {
                 }
             }
             delete.getResponseBodyAsString();   // exhaust the response, although not interesting
-            result = new RemoteOperationResult((delete.succeeded() || status == HttpStatus.SC_NOT_FOUND), status);
+            result = new RemoteOperationResult((delete.succeeded() || status == HttpStatus.SC_NOT_FOUND), status, delete.getResponseHeaders());
             Log_OC.i(TAG, "Remove " + mFileToRemove.getRemotePath() + ": " + result.getLogMessage());
             
         } catch (Exception e) {
index 1c636fb..fddb849 100644 (file)
@@ -136,7 +136,7 @@ public class RenameFileOperation extends RemoteOperation {
             }
             
             move.getResponseBodyAsString(); // exhaust response, although not interesting
-            result = new RemoteOperationResult(move.succeeded(), status);
+            result = new RemoteOperationResult(move.succeeded(), status, move.getResponseHeaders());
             Log_OC.i(TAG, "Rename " + mFile.getRemotePath() + " to " + mNewRemotePath + ": " + result.getLogMessage());
             
         } catch (Exception e) {
index 3022a53..cb4485e 100644 (file)
@@ -101,7 +101,7 @@ public class SynchronizeFileOperation extends RemoteOperation {
                         
                     } else {
                         client.exhaustResponse(propfind.getResponseBodyAsStream());
-                        result = new RemoteOperationResult(false, status);
+                        result = new RemoteOperationResult(false, status, propfind.getResponseHeaders());
                     }
                 }
                 
index af1c5e9..68d539c 100644 (file)
@@ -29,6 +29,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Vector;
 
+import org.apache.commons.httpclient.Header;
 import org.apache.http.HttpStatus;
 import org.apache.jackrabbit.webdav.MultiStatus;
 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
@@ -237,9 +238,9 @@ public class SynchronizeFolderOperation extends RemoteOperation {
                         } else {
                             mFailsInFavouritesFound++;
                             if (contentsResult.getException() != null) {
-                                Log_OC.d(TAG, "Error while synchronizing favourites : " +  contentsResult.getLogMessage(), contentsResult.getException());
+                                Log_OC.e(TAG, "Error while synchronizing favourites : " +  contentsResult.getLogMessage(), contentsResult.getException());
                             } else {
-                                Log_OC.d(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
+                                Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
                             }
                         }
                     }   // won't let these fails break the synchronization process
@@ -278,21 +279,29 @@ public class SynchronizeFolderOperation extends RemoteOperation {
                     result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);   // should be different result, but will do the job
 
                 } else {
-                    result = new RemoteOperationResult(true, status);
+                    result = new RemoteOperationResult(true, status, query.getResponseHeaders());
                 }
             } else {
-                result = new RemoteOperationResult(false, status);
+                result = new RemoteOperationResult(false, status, query.getResponseHeaders());
             }
             Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
 
-
         } catch (Exception e) {
             result = new RemoteOperationResult(e);
-            Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
+            
 
         } finally {
             if (query != null)
                 query.releaseConnection();  // let the connection available for other methods
+            if (result.isSuccess()) {
+                Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
+            } else {
+                if (result.isException()) {
+                    Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
+                } else {
+                    Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
+                }
+            }
         }
 
         return result;
index 1b56bfb..1643377 100644 (file)
@@ -65,7 +65,7 @@ public class UpdateOCVersionOperation extends RemoteOperation {
             int status = client.executeMethod(get);
             if (status != HttpStatus.SC_OK) {
                 client.exhaustResponse(get.getResponseBodyAsStream());
-                result = new RemoteOperationResult(false, status);
+                result = new RemoteOperationResult(false, status, get.getResponseHeaders());
                 
             } else {
                 String response = get.getResponseBodyAsString();
index 2c891be..cae1f17 100644 (file)
@@ -304,7 +304,7 @@ public class UploadFileOperation extends RemoteOperation {
                 }
             }
 
-            result = new RemoteOperationResult(isSuccess(status), status);
+            result = new RemoteOperationResult(isSuccess(status), status, (mPutMethod != null ? mPutMethod.getResponseHeaders() : null));
 
         } catch (Exception e) {
             // TODO something cleaner with cancellations
index 3398f03..cc70d63 100644 (file)
@@ -189,6 +189,8 @@ public class FileContentProvider extends ContentProvider {
         }
 
         SQLiteDatabase db = mDbHelper.getReadableDatabase();
+        // DB case_sensitive
+        db.execSQL("PRAGMA case_sensitive_like = true");
         Cursor c = sqlQuery.query(db, projection, selection, selectionArgs,
                 null, null, order);
 
index 8653fe7..49f88f9 100644 (file)
@@ -28,6 +28,7 @@ import org.apache.jackrabbit.webdav.DavException;
 
 import com.owncloud.android.Log_OC;
 import com.owncloud.android.R;
+import com.owncloud.android.authentication.AccountAuthenticator;
 import com.owncloud.android.authentication.AuthenticatorActivity;
 import com.owncloud.android.datamodel.DataStorageManager;
 import com.owncloud.android.datamodel.FileDataStorageManager;
@@ -223,7 +224,10 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
             sendStickyBroadcast(true, remotePath, null);
             
         } else {
-            if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED) {
+            if (result.getCode() == RemoteOperationResult.ResultCode.UNAUTHORIZED ||
+                   // (result.isTemporalRedirection() && result.isIdPRedirection() &&
+                    ( result.isIdPRedirection() && 
+                            AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(getClient().getAuthTokenType()))) {
                 mSyncResult.stats.numAuthExceptions++;
                 
             } else if (result.getException() instanceof DavException) {
@@ -304,7 +308,13 @@ public class FileSyncAdapter extends AbstractOwnCloudSyncAdapter {
     private void notifyFailedSynchronization() {
         Notification notification = new Notification(R.drawable.icon, getContext().getString(R.string.sync_fail_ticker), System.currentTimeMillis());
         notification.flags |= Notification.FLAG_AUTO_CANCEL;
-        boolean needsToUpdateCredentials = (mLastFailedResult != null && mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED);
+        boolean needsToUpdateCredentials = (mLastFailedResult != null && 
+                                             (  mLastFailedResult.getCode() == ResultCode.UNAUTHORIZED ||
+                                                // (mLastFailedResult.isTemporalRedirection() && mLastFailedResult.isIdPRedirection() && 
+                                                ( mLastFailedResult.isIdPRedirection() && 
+                                                 AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(getClient().getAuthTokenType()))
+                                             )
+                                           );
         // TODO put something smart in the contentIntent below for all the possible errors
         notification.contentIntent = PendingIntent.getActivity(getContext().getApplicationContext(), (int)System.currentTimeMillis(), new Intent(), 0);
         if (needsToUpdateCredentials) {
index 1a1cd51..2c3448d 100644 (file)
@@ -50,6 +50,7 @@ import com.actionbarsherlock.view.MenuItem;
 import com.owncloud.android.authentication.AccountAuthenticator;
 import com.owncloud.android.authentication.AuthenticatorActivity;
 import com.owncloud.android.authentication.AccountUtils;
+import com.owncloud.android.ui.activity.FileActivity.AccountCreationCallback;
 import com.owncloud.android.Log_OC;
 
 import com.owncloud.android.R;
@@ -133,11 +134,20 @@ public class AccountSelectActivity extends SherlockListActivity implements
     @Override
     public boolean onMenuItemSelected(int featureId, MenuItem item) {
         if (item.getItemId() == R.id.createAccount) {
-            Intent intent = new Intent(
+            /*Intent intent = new Intent(
                     android.provider.Settings.ACTION_ADD_ACCOUNT);
             intent.putExtra("authorities",
                     new String[] { AccountAuthenticator.AUTHORITY });
-            startActivity(intent);
+            startActivity(intent);*/
+            AccountManager am = AccountManager.get(getApplicationContext());
+            am.addAccount(AccountAuthenticator.ACCOUNT_TYPE, 
+                            null,
+                            null, 
+                            null, 
+                            this, 
+                            null,                        
+                            null);
+            
             return true;
         }
         return false;
index a23b3be..2e47ce0 100644 (file)
@@ -174,7 +174,7 @@ public abstract class FileActivity extends SherlockFragmentActivity {
     private void createFirstAccount() {
         AccountManager am = AccountManager.get(getApplicationContext());
         am.addAccount(AccountAuthenticator.ACCOUNT_TYPE, 
-                        AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD,
+                        null,
                         null, 
                         null, 
                         this, 
diff --git a/src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java b/src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java
new file mode 100644 (file)
index 0000000..a5219a2
--- /dev/null
@@ -0,0 +1,284 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013 ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License version 2,
+ *   as published by the Free Software Foundation.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.ui.dialog;
+
+import android.annotation.SuppressLint;
+import android.app.Activity;
+import android.app.Dialog;
+import android.content.DialogInterface;
+import android.os.Bundle;
+import android.os.Handler;
+import android.support.v4.app.FragmentTransaction;
+import android.support.v4.app.FragmentManager;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.webkit.CookieManager;
+import android.webkit.CookieSyncManager;
+import android.webkit.WebBackForwardList;
+import android.webkit.WebSettings;
+import android.webkit.WebView;
+
+import com.actionbarsherlock.app.SherlockDialogFragment;
+import com.owncloud.android.Log_OC;
+import com.owncloud.android.R;
+import com.owncloud.android.authentication.SsoWebViewClient;
+import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;
+
+import eu.alefzero.webdav.WebdavClient;
+
+/**
+ * Dialog to show the WebView for SAML Authentication
+ * 
+ * @author Maria Asensio
+ * @author David A. Velasco
+ */
+public class SamlWebViewDialog extends SherlockDialogFragment {
+
+    public final String SAML_DIALOG_TAG = "SamlWebViewDialog";
+    
+    private final static String TAG =  SamlWebViewDialog.class.getSimpleName();
+
+    private static final String ARG_INITIAL_URL = "INITIAL_URL";
+    private static final String ARG_TARGET_URL = "TARGET_URL";
+    private static final String KEY_WEBVIEW_STATE = "WEBVIEW_STATE";
+    
+    private WebView mSsoWebView;
+    private SsoWebViewClient mWebViewClient;
+    
+    private String mInitialUrl;
+    private String mTargetUrl;
+    
+    private Handler mHandler;
+
+    private SsoWebViewClientListener mSsoWebViewClientListener;
+
+    //private View mSsoRootView;
+
+
+    /**
+     * Public factory method to get dialog instances.
+     * 
+     * @param handler
+     * @param Url           Url to open at WebView
+     * @param targetURL     mHostBaseUrl + AccountUtils.getWebdavPath(mDiscoveredVersion, mCurrentAuthTokenType)
+     * @return              New dialog instance, ready to show.
+     */
+    public static SamlWebViewDialog newInstance(String url, String targetUrl) {
+        Log_OC.d(TAG, "New instance");
+        SamlWebViewDialog fragment = new SamlWebViewDialog();
+        Bundle args = new Bundle();
+        args.putString(ARG_INITIAL_URL, url);
+        args.putString(ARG_TARGET_URL, targetUrl);
+        fragment.setArguments(args);
+        return fragment;
+    }
+    
+    
+    public SamlWebViewDialog() {
+        super();
+        Log_OC.d(TAG, "constructor");
+    }
+    
+    
+    @Override
+    public void onAttach(Activity activity) {
+        Log_OC.d(TAG, "onAttach");
+        super.onAttach(activity);
+        try {
+            mSsoWebViewClientListener = (SsoWebViewClientListener) activity;
+            mHandler = new Handler();
+            mWebViewClient = new SsoWebViewClient(mHandler, mSsoWebViewClientListener);
+            
+       } catch (ClassCastException e) {
+            throw new ClassCastException(activity.toString() + " must implement " + SsoWebViewClientListener.class.getSimpleName());
+        }
+    }
+
+    
+    @SuppressLint("SetJavaScriptEnabled")
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        Log_OC.d(TAG, "onCreate");
+        super.onCreate(savedInstanceState);
+        
+        CookieSyncManager.createInstance(getActivity());
+
+        if (savedInstanceState == null) {
+            mInitialUrl = getArguments().getString(ARG_INITIAL_URL);
+            mTargetUrl = getArguments().getString(ARG_TARGET_URL);
+        } else {
+            mInitialUrl = savedInstanceState.getString(ARG_INITIAL_URL);
+            mTargetUrl = savedInstanceState.getString(ARG_TARGET_URL);
+        }
+        
+        setStyle(SherlockDialogFragment.STYLE_NO_TITLE, R.style.Theme_ownCloud_Dialog);
+    }
+    
+    @Override
+    public Dialog onCreateDialog(Bundle savedInstanceState) {
+        Log_OC.d(TAG, "onCreateDialog");
+
+        /*
+        // build the dialog
+        AlertDialog.Builder builder = new AlertDialog.Builder(getSherlockActivity());
+        if (mSsoRootView.getParent() != null) {
+            ((ViewGroup)(mSsoRootView.getParent())).removeView(mSsoRootView);
+        }
+        builder.setView(mSsoRootView);
+        //builder.setView(mSsoWebView);
+        Dialog dialog = builder.create();
+        */
+        
+        return super.onCreateDialog(savedInstanceState);
+    }
+
+    @SuppressLint("SetJavaScriptEnabled")
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+        Log_OC.d(TAG, "onCreateView");
+        
+        // Inflate layout of the dialog  
+        View rootView = inflater.inflate(R.layout.sso_dialog, container, false);  // null parent view because it will go in the dialog layout
+        mSsoWebView  = (WebView) rootView.findViewById(R.id.sso_webview);
+            
+        mWebViewClient.setTargetUrl(mTargetUrl);
+        mSsoWebView.setWebViewClient(mWebViewClient);
+        
+        if (savedInstanceState == null) {
+            Log_OC.d(TAG,  "   initWebView start");
+            CookieManager cookieManager = CookieManager.getInstance();
+            cookieManager.setAcceptCookie(true);
+            cookieManager.removeAllCookie();
+            mSsoWebView.loadUrl(mInitialUrl);
+            
+        } else {
+            Log_OC.d(TAG, "   restoreWebView start");
+            WebBackForwardList history = mSsoWebView.restoreState(savedInstanceState.getBundle(KEY_WEBVIEW_STATE));
+            if (history == null) {
+                Log_OC.e(TAG, "Error restoring WebView state ; back to starting URL");
+                mSsoWebView.loadUrl(mInitialUrl);
+            }
+        }
+
+        WebSettings webSettings = mSsoWebView.getSettings();
+        webSettings.setJavaScriptEnabled(true);
+        webSettings.setBuiltInZoomControls(true);
+        webSettings.setLoadWithOverviewMode(false);
+        webSettings.setSavePassword(false);
+        webSettings.setUserAgentString(WebdavClient.USER_AGENT);
+        webSettings.setSaveFormData(false);
+        
+        return rootView;
+    }
+
+    @Override
+    public void onSaveInstanceState(Bundle outState) {
+        Log_OC.d(SAML_DIALOG_TAG, "onSaveInstanceState being CALLED");
+        super.onSaveInstanceState(outState);
+        
+        // save URLs
+        outState.putString(ARG_INITIAL_URL, mInitialUrl);
+        outState.putString(ARG_TARGET_URL, mTargetUrl);
+        
+        // Save the state of the WebView
+        Bundle webviewState = new Bundle();
+        mSsoWebView.saveState(webviewState);
+        outState.putBundle(KEY_WEBVIEW_STATE, webviewState);
+    }
+
+    @Override
+    public void onDestroyView() {
+        Log_OC.d(TAG, "onDestroyView");
+        
+        mSsoWebView.setWebViewClient(null);
+        
+        // Work around bug: http://code.google.com/p/android/issues/detail?id=17423
+        Dialog dialog = getDialog();
+        if ((dialog != null)) {
+            dialog.setOnDismissListener(null);
+            //dialog.dismiss();
+            //dialog.setDismissMessage(null);
+        }
+        
+        super.onDestroyView();
+    }
+    
+    @Override
+    public void onDestroy() {
+        Log_OC.d(TAG, "onDestroy");
+        super.onDestroy();
+    }
+
+    @Override
+    public void onDetach() {
+        Log_OC.d(TAG, "onDetach");
+        mSsoWebViewClientListener = null;
+        mWebViewClient = null;
+        super.onDetach();
+    }
+    
+    @Override
+    public void onCancel (DialogInterface dialog) {
+        Log_OC.d(SAML_DIALOG_TAG, "onCancel");
+        super.onCancel(dialog);
+    }
+    
+    @Override
+    public void onDismiss (DialogInterface dialog) {
+        Log_OC.d(SAML_DIALOG_TAG, "onDismiss");
+        super.onDismiss(dialog);
+    }
+    
+    @Override
+    public void onStart() {
+        Log_OC.d(SAML_DIALOG_TAG, "onStart");
+        super.onStart();
+    }
+
+    @Override
+    public void onStop() {
+        Log_OC.d(SAML_DIALOG_TAG, "onStop");
+        super.onStop();
+    }
+
+    @Override
+    public void onResume() {
+        Log_OC.d(SAML_DIALOG_TAG, "onResume");
+        super.onResume();
+    }
+
+    @Override
+    public void onPause() {
+        Log_OC.d(SAML_DIALOG_TAG, "onPause");
+        super.onPause();
+    }
+    
+    @Override
+    public int show (FragmentTransaction transaction, String tag) {
+        Log_OC.d(SAML_DIALOG_TAG, "show (transaction)");
+        return super.show(transaction, tag);
+    }
+
+    @Override
+    public void show (FragmentManager manager, String tag) {
+        Log_OC.d(SAML_DIALOG_TAG, "show (manager)");
+        super.show(manager, tag);
+    }
+
+}
\ No newline at end of file
diff --git a/src/com/owncloud/android/ui/dialog/SsoWebView.java b/src/com/owncloud/android/ui/dialog/SsoWebView.java
new file mode 100644 (file)
index 0000000..3a71139
--- /dev/null
@@ -0,0 +1,40 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013 ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License version 2,
+ *   as published by the Free Software Foundation.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.ui.dialog;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.webkit.WebView;
+
+public class SsoWebView extends WebView {
+    
+    public SsoWebView(Context context) {
+        super(context);
+    }
+    
+    public SsoWebView(Context context, AttributeSet attr) {
+        super(context, attr);
+    }
+    
+    @Override
+    public boolean onCheckIsTextEditor () {
+        return false;
+    }
+    
+}
+
index fdabebe..cedf926 100644 (file)
 
 package eu.alefzero.webdav;
 
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.List;
 
 import org.apache.commons.httpclient.Credentials;
-import org.apache.commons.httpclient.HostConfiguration;
 import org.apache.commons.httpclient.HttpClient;
 import org.apache.commons.httpclient.HttpConnectionManager;
 import org.apache.commons.httpclient.HttpException;
 import org.apache.commons.httpclient.HttpMethod;
 import org.apache.commons.httpclient.HttpMethodBase;
-import org.apache.commons.httpclient.HttpState;
 import org.apache.commons.httpclient.HttpVersion;
 import org.apache.commons.httpclient.UsernamePasswordCredentials;
 import org.apache.commons.httpclient.auth.AuthPolicy;
 import org.apache.commons.httpclient.auth.AuthScope;
-import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.cookie.CookiePolicy;
 import org.apache.commons.httpclient.methods.HeadMethod;
-import org.apache.commons.httpclient.methods.PutMethod;
 import org.apache.commons.httpclient.params.HttpMethodParams;
 import org.apache.http.HttpStatus;
 import org.apache.http.params.CoreProtocolPNames;
-import org.apache.jackrabbit.webdav.client.methods.DavMethod;
-import org.apache.jackrabbit.webdav.client.methods.DeleteMethod;
 
 import com.owncloud.android.Log_OC;
 
+import com.owncloud.android.authentication.AccountAuthenticator;
 import com.owncloud.android.network.BearerAuthScheme;
 import com.owncloud.android.network.BearerCredentials;
 
@@ -57,10 +50,12 @@ import android.net.Uri;
 public class WebdavClient extends HttpClient {
     private Uri mUri;
     private Credentials mCredentials;
+    private boolean mFollowRedirects;
+    private String mSsoSessionCookie;
+    private String mAuthTokenType;
     final private static String TAG = "WebdavClient";
-    private static final String USER_AGENT = "Android-ownCloud";
+    public static final String USER_AGENT = "Android-ownCloud";
     
-    private OnDatatransferProgressListener mDataTransferListener;
     static private byte[] sExhaustBuffer = new byte[1024];
     
     /**
@@ -71,6 +66,9 @@ public class WebdavClient extends HttpClient {
         Log_OC.d(TAG, "Creating WebdavClient");
         getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
         getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
+        mFollowRedirects = true;
+        mSsoSessionCookie = null;
+        mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
     }
 
     public void setBearerCredentials(String accessToken) {
@@ -82,6 +80,8 @@ public class WebdavClient extends HttpClient {
         
         mCredentials = new BearerCredentials(accessToken);
         getState().setCredentials(AuthScope.ANY, mCredentials);
+        mSsoSessionCookie = null;
+        mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN;
     }
 
     public void setBasicCredentials(String username, String password) {
@@ -92,8 +92,19 @@ public class WebdavClient extends HttpClient {
         getParams().setAuthenticationPreemptive(true);
         mCredentials = new UsernamePasswordCredentials(username, password);
         getState().setCredentials(AuthScope.ANY, mCredentials);
+        mSsoSessionCookie = null;
+        mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
     }
     
+    public void setSsoSessionCookie(String accessToken) {
+        getParams().setAuthenticationPreemptive(false);
+        getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
+        mSsoSessionCookie = accessToken;
+        mCredentials = null;
+        mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE;
+    }
+    
+    
     /**
      * Check if a file exists in the OC server
      * 
@@ -145,6 +156,21 @@ public class WebdavClient extends HttpClient {
             getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout);
         }
     }
+    
+    
+    @Override
+    public int executeMethod(HttpMethod method) throws IOException, HttpException {
+        try {
+            method.setFollowRedirects(mFollowRedirects);
+        } catch (Exception e) {
+            
+        }
+        if (mSsoSessionCookie != null && mSsoSessionCookie.length() > 0) {
+            method.setRequestHeader("Cookie", mSsoSessionCookie);
+        }
+        return super.executeMethod(method);
+    }
+
 
     /**
      * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
@@ -185,6 +211,18 @@ public class WebdavClient extends HttpClient {
 
     public final Credentials getCredentials() {\r
         return mCredentials;\r
-    }\r
-\r
+    }
+    
+    public final String getSsoSessionCookie() {
+        return mSsoSessionCookie;
+    }
+
+    public void setFollowRedirects(boolean followRedirects) {
+        mFollowRedirects = followRedirects;
+    }
+
+    public String getAuthTokenType() {
+        return mAuthTokenType;
+    }
+
 }