Fixed cancel button in landscape account activity
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / files / services / FileDownloader.java
index cc13a67..b0dd2b2 100644 (file)
@@ -1,7 +1,9 @@
 package eu.alefzero.owncloud.files.services;\r
 \r
 import java.io.File;\r
 package eu.alefzero.owncloud.files.services;\r
 \r
 import java.io.File;\r
-import java.io.IOException;\r
+import java.util.Collections;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
 \r
 import android.accounts.Account;\r
 import android.accounts.AccountManager;\r
 \r
 import android.accounts.Account;\r
 import android.accounts.AccountManager;\r
@@ -21,21 +23,21 @@ import android.os.Message;
 import android.os.Process;\r
 import android.util.Log;\r
 import android.widget.RemoteViews;\r
 import android.os.Process;\r
 import android.util.Log;\r
 import android.widget.RemoteViews;\r
-import eu.alefzero.owncloud.AccountUtils;\r
 import eu.alefzero.owncloud.R;\r
 import eu.alefzero.owncloud.R;\r
-import eu.alefzero.owncloud.R.drawable;\r
 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;\r
 import eu.alefzero.owncloud.db.ProviderMeta.ProviderTableMeta;\r
 import eu.alefzero.owncloud.files.interfaces.OnDatatransferProgressListener;\r
 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;\r
 import eu.alefzero.owncloud.db.ProviderMeta.ProviderTableMeta;\r
 import eu.alefzero.owncloud.files.interfaces.OnDatatransferProgressListener;\r
-import eu.alefzero.owncloud.ui.activity.FileDisplayActivity;\r
-import eu.alefzero.owncloud.utils.OwnCloudVersion;\r
 import eu.alefzero.webdav.WebdavClient;\r
 \r
 public class FileDownloader extends Service implements OnDatatransferProgressListener {\r
     public static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";\r
 import eu.alefzero.webdav.WebdavClient;\r
 \r
 public class FileDownloader extends Service implements OnDatatransferProgressListener {\r
     public static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";\r
+    public static final String EXTRA_DOWNLOAD_RESULT = "RESULT";    \r
     public static final String EXTRA_ACCOUNT = "ACCOUNT";\r
     public static final String EXTRA_FILE_PATH = "FILE_PATH";\r
     public static final String EXTRA_ACCOUNT = "ACCOUNT";\r
     public static final String EXTRA_FILE_PATH = "FILE_PATH";\r
+    public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";\r
     public static final String EXTRA_FILE_SIZE = "FILE_SIZE";\r
     public static final String EXTRA_FILE_SIZE = "FILE_SIZE";\r
+    public static final String ACCOUNT_NAME = "ACCOUNT_NAME";\r
+    \r
     private static final String TAG = "FileDownloader";\r
 \r
     private NotificationManager mNotificationMngr;\r
     private static final String TAG = "FileDownloader";\r
 \r
     private NotificationManager mNotificationMngr;\r
@@ -43,11 +45,32 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
     private ServiceHandler mServiceHandler;\r
     private Account mAccount;\r
     private String mFilePath;\r
     private ServiceHandler mServiceHandler;\r
     private Account mAccount;\r
     private String mFilePath;\r
+    private String mRemotePath;\r
     private int mLastPercent;\r
     private long mTotalDownloadSize;\r
     private int mLastPercent;\r
     private long mTotalDownloadSize;\r
-    private long mCurrentDownlodSize;\r
+    private long mCurrentDownloadSize;\r
     private Notification mNotification;\r
     private Notification mNotification;\r
+    \r
+    /**\r
+     * Static map with the files being download and the path to the temporal file were are download\r
+     */\r
+    private static Map<String, String> mDownloadsInProgress = Collections.synchronizedMap(new HashMap<String, String>());\r
+    \r
+    /**\r
+     * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading\r
+     */\r
+    public static boolean isDownloading(Account account, String remotePath) {\r
+        return (mDownloadsInProgress.get(buildRemoteName(account.name, remotePath)) != null);\r
+    }\r
+    \r
+    /**\r
+     * Builds a key for mDownloadsInProgress from the accountName and remotePath\r
+     */\r
+    private static String buildRemoteName(String accountName, String remotePath) {\r
+        return accountName + remotePath;\r
+    }\r
 \r
 \r
+    \r
     private final class ServiceHandler extends Handler {\r
         public ServiceHandler(Looper looper) {\r
             super(looper);\r
     private final class ServiceHandler extends Handler {\r
         public ServiceHandler(Looper looper) {\r
             super(looper);\r
@@ -59,6 +82,18 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
             stopSelf(msg.arg1);\r
         }\r
     }\r
             stopSelf(msg.arg1);\r
         }\r
     }\r
+    \r
+    public static final String getSavePath(String accountName) {\r
+        File sdCard = Environment.getExternalStorageDirectory();\r
+        return sdCard.getAbsolutePath() + "/owncloud/" + Uri.encode(accountName, "@");   \r
+            // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names, that can be in the accountName since 0.1.190B\r
+    }\r
+    \r
+    public static final String getTemporalPath(String accountName) {\r
+        File sdCard = Environment.getExternalStorageDirectory();\r
+        return sdCard.getAbsolutePath() + "/owncloud/tmp/" + Uri.encode(accountName, "@");\r
+            // URL encoding is an 'easy fix' to overcome that NTFS and FAT32 don't allow ":" in file names, that can be in the accountName since 0.1.190B\r
+    }\r
 \r
     @Override\r
     public void onCreate() {\r
 \r
     @Override\r
     public void onCreate() {\r
@@ -78,95 +113,140 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
 \r
     @Override\r
     public int onStartCommand(Intent intent, int flags, int startId) {\r
 \r
     @Override\r
     public int onStartCommand(Intent intent, int flags, int startId) {\r
-        if (!intent.hasExtra(EXTRA_ACCOUNT)\r
-                && !intent.hasExtra(EXTRA_FILE_PATH)) {\r
+        if (    !intent.hasExtra(EXTRA_ACCOUNT) ||\r
+                !intent.hasExtra(EXTRA_FILE_PATH) ||\r
+                !intent.hasExtra(EXTRA_REMOTE_PATH)\r
+           ) {\r
             Log.e(TAG, "Not enough information provided in intent");\r
             Log.e(TAG, "Not enough information provided in intent");\r
-            return START_STICKY;\r
+            return START_NOT_STICKY;\r
         }\r
         mAccount = intent.getParcelableExtra(EXTRA_ACCOUNT);\r
         mFilePath = intent.getStringExtra(EXTRA_FILE_PATH);\r
         }\r
         mAccount = intent.getParcelableExtra(EXTRA_ACCOUNT);\r
         mFilePath = intent.getStringExtra(EXTRA_FILE_PATH);\r
+        mRemotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);\r
+        mTotalDownloadSize = intent.getLongExtra(EXTRA_FILE_SIZE, -1);\r
+        mCurrentDownloadSize = mLastPercent = 0;\r
+\r
         Message msg = mServiceHandler.obtainMessage();\r
         msg.arg1 = startId;\r
         mServiceHandler.sendMessage(msg);\r
         Message msg = mServiceHandler.obtainMessage();\r
         msg.arg1 = startId;\r
         mServiceHandler.sendMessage(msg);\r
-        mCurrentDownlodSize = mLastPercent = 0;\r
-        mTotalDownloadSize = intent.getLongExtra(EXTRA_FILE_SIZE, -1);\r
 \r
         return START_NOT_STICKY;\r
     }\r
 \r
 \r
         return START_NOT_STICKY;\r
     }\r
 \r
-    void downloadFile() {\r
-        AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);\r
-        String oc_base_url = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);\r
-        OwnCloudVersion ocv = new OwnCloudVersion(am\r
-                .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));\r
-        String webdav_path = AccountUtils.getWebdavPath(ocv);\r
-        Uri oc_url = Uri.parse(oc_base_url+webdav_path);\r
+    /**\r
+     * Core download method: requests the file to download and stores it.\r
+     */\r
+    private void downloadFile() {\r
+        boolean downloadResult = false;\r
 \r
 \r
-        WebdavClient wdc = new WebdavClient(Uri.parse(oc_base_url + webdav_path));\r
-        \r
+        /// prepare client object to send the request to the ownCloud server\r
+        AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);\r
+        WebdavClient wdc = new WebdavClient(mAccount, getApplicationContext());\r
         String username = mAccount.name.split("@")[0];\r
         String username = mAccount.name.split("@")[0];\r
-        String password = "";\r
+        String password = null;\r
         try {\r
             password = am.blockingGetAuthToken(mAccount,\r
                     AccountAuthenticator.AUTH_TOKEN_TYPE, true);\r
         } catch (Exception e) {\r
         try {\r
             password = am.blockingGetAuthToken(mAccount,\r
                     AccountAuthenticator.AUTH_TOKEN_TYPE, true);\r
         } catch (Exception e) {\r
-            e.printStackTrace();\r
+            Log.e(TAG, "Access to account credentials failed", e);\r
+            sendFinalBroadcast(downloadResult, null);\r
             return;\r
         }\r
             return;\r
         }\r
-\r
         wdc.setCredentials(username, password);\r
         wdc.allowSelfsignedCertificates();\r
         wdc.setDataTransferProgressListener(this);\r
 \r
         wdc.setCredentials(username, password);\r
         wdc.allowSelfsignedCertificates();\r
         wdc.setDataTransferProgressListener(this);\r
 \r
-        mNotification = new Notification(R.drawable.icon, "Downloading file", System.currentTimeMillis());\r
-\r
+        \r
+        /// download will be in a temporal file\r
+        File tmpFile = new File(getTemporalPath(mAccount.name) + mFilePath);\r
+        \r
+        /// create status notification to show the download progress\r
+        mNotification = new Notification(R.drawable.icon, getString(R.string.downloader_download_in_progress_ticker), System.currentTimeMillis());\r
         mNotification.flags |= Notification.FLAG_ONGOING_EVENT;\r
         mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);\r
         mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, mTotalDownloadSize == -1);\r
         mNotification.flags |= Notification.FLAG_ONGOING_EVENT;\r
         mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);\r
         mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, mTotalDownloadSize == -1);\r
+        mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), 0, tmpFile.getName()));\r
         mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);\r
         mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);\r
+        // TODO put something smart in the contentIntent below\r
+        mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);\r
+        mNotificationMngr.notify(R.string.downloader_download_in_progress_ticker, mNotification);\r
         \r
         \r
-        mNotificationMngr.notify(1, mNotification);\r
 \r
 \r
-        File sdCard = Environment.getExternalStorageDirectory();\r
-        File file = new File(sdCard.getAbsolutePath() + "/owncloud/" + mAccount.name + mFilePath);\r
+        /// perform the download\r
+        tmpFile.getParentFile().mkdirs();\r
+        mDownloadsInProgress.put(buildRemoteName(mAccount.name, mRemotePath), tmpFile.getAbsolutePath());\r
+        File newFile = null;\r
         try {\r
         try {\r
-            file.getParentFile().mkdirs();\r
-            file.createNewFile();\r
-        } catch (IOException e) {\r
-            e.printStackTrace();\r
+            if (wdc.downloadFile(mRemotePath, tmpFile)) {\r
+                newFile = new File(getSavePath(mAccount.name) + mFilePath);\r
+                newFile.getParentFile().mkdirs();\r
+                boolean moved = tmpFile.renameTo(newFile);\r
+            \r
+                if (moved) {\r
+                    ContentValues cv = new ContentValues();\r
+                    cv.put(ProviderTableMeta.FILE_STORAGE_PATH, newFile.getAbsolutePath());\r
+                    getContentResolver().update(\r
+                            ProviderTableMeta.CONTENT_URI,\r
+                            cv,\r
+                            ProviderTableMeta.FILE_NAME + "=? AND "\r
+                                    + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",\r
+                            new String[] {\r
+                                mFilePath.substring(mFilePath.lastIndexOf('/') + 1),\r
+                                mAccount.name });\r
+                    downloadResult = true;\r
+                }\r
+            }\r
+        } finally {\r
+            mDownloadsInProgress.remove(buildRemoteName(mAccount.name, mRemotePath));\r
         }\r
 \r
         }\r
 \r
-        Log.e(TAG, file.getAbsolutePath() + " " + oc_url.toString());\r
-        Log.e(TAG, mFilePath+"");\r
-        if (wdc.downloadFile(mFilePath, file)) {\r
-            ContentValues cv = new ContentValues();\r
-            cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getAbsolutePath());\r
-            getContentResolver().update(\r
-                    ProviderTableMeta.CONTENT_URI,\r
-                    cv,\r
-                    ProviderTableMeta.FILE_NAME + "=? AND "\r
-                            + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",\r
-                    new String[] {\r
-                            mFilePath.substring(mFilePath.lastIndexOf('/') + 1),\r
-                            mAccount.name });            \r
-        }\r
-        mNotificationMngr.cancel(1);\r
-        Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);\r
-        end.putExtra(EXTRA_FILE_PATH, file.getAbsolutePath());\r
-        sendBroadcast(end);\r
+        \r
+        /// notify result\r
+        mNotificationMngr.cancel(R.string.downloader_download_in_progress_ticker);\r
+        int tickerId = (downloadResult) ? R.string.downloader_download_succeeded_ticker : R.string.downloader_download_failed_ticker;\r
+        int contentId = (downloadResult) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;\r
+        Notification finalNotification = new Notification(R.drawable.icon, getString(tickerId), System.currentTimeMillis());\r
+        finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;\r
+        // TODO put something smart in the contentIntent below\r
+        finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);\r
+        finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), tmpFile.getName()), finalNotification.contentIntent);\r
+        mNotificationMngr.notify(tickerId, finalNotification);\r
+            \r
+        sendFinalBroadcast(downloadResult, (downloadResult)?newFile.getAbsolutePath():null);\r
     }\r
 \r
     }\r
 \r
+    /**\r
+     * Callback method to update the progress bar in the status notification.\r
+     */\r
     @Override\r
     public void transferProgress(long progressRate) {\r
     @Override\r
     public void transferProgress(long progressRate) {\r
-        mCurrentDownlodSize += progressRate;\r
-        int percent = (int)(100.0*((double)mCurrentDownlodSize)/((double)mTotalDownloadSize));\r
+        mCurrentDownloadSize += progressRate;\r
+        int percent = (int)(100.0*((double)mCurrentDownloadSize)/((double)mTotalDownloadSize));\r
         if (percent != mLastPercent) {\r
         if (percent != mLastPercent) {\r
-          mNotification.contentView.setProgressBar(R.id.status_progress, 100, (int)(100*mCurrentDownlodSize/mTotalDownloadSize), mTotalDownloadSize == -1);\r
-          mNotification.contentView.setTextViewText(R.id.status_text, percent+"%");\r
-          mNotificationMngr.notify(1, mNotification);\r
+          mNotification.contentView.setProgressBar(R.id.status_progress, 100, (int)(100*mCurrentDownloadSize/mTotalDownloadSize), mTotalDownloadSize == -1);\r
+          mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), percent, new File(mFilePath).getName()));\r
+          mNotificationMngr.notify(R.string.downloader_download_in_progress_ticker, mNotification);\r
         }\r
         \r
         mLastPercent = percent;\r
     }\r
         }\r
         \r
         mLastPercent = percent;\r
     }\r
+    \r
+\r
+    /**\r
+     * Sends a broadcast in order to the interested activities can update their view\r
+     * \r
+     * @param downloadResult        'True' if the download was successful\r
+     * @param newFilePath           Absolute path to the download file\r
+     */\r
+    private void sendFinalBroadcast(boolean downloadResult, String newFilePath) {\r
+        Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);\r
+        end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult);\r
+        end.putExtra(ACCOUNT_NAME, mAccount.name);\r
+        end.putExtra(EXTRA_REMOTE_PATH, mRemotePath);\r
+        if (downloadResult) {\r
+            end.putExtra(EXTRA_FILE_PATH, newFilePath);\r
+        }\r
+        sendBroadcast(end);\r
+    }\r
 \r
 }\r
 \r
 }\r