1 package com
.owncloud
.android
.files
.services
;
4 import java
.util
.Collections
;
5 import java
.util
.HashMap
;
8 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
9 import com
.owncloud
.android
.db
.ProviderMeta
.ProviderTableMeta
;
10 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
11 import com
.owncloud
.android
.utils
.OwnCloudClientUtils
;
13 import android
.accounts
.Account
;
14 import android
.accounts
.AccountManager
;
15 import android
.app
.Notification
;
16 import android
.app
.NotificationManager
;
17 import android
.app
.PendingIntent
;
18 import android
.app
.Service
;
19 import android
.content
.ContentValues
;
20 import android
.content
.Intent
;
21 import android
.net
.Uri
;
22 import android
.os
.Environment
;
23 import android
.os
.Handler
;
24 import android
.os
.HandlerThread
;
25 import android
.os
.IBinder
;
26 import android
.os
.Looper
;
27 import android
.os
.Message
;
28 import android
.os
.Process
;
29 import android
.util
.Log
;
30 import android
.widget
.RemoteViews
;
31 import com
.owncloud
.android
.R
;
32 import eu
.alefzero
.webdav
.WebdavClient
;
34 public class FileDownloader
extends Service
implements OnDatatransferProgressListener
{
35 public static final String DOWNLOAD_FINISH_MESSAGE
= "DOWNLOAD_FINISH";
36 public static final String EXTRA_DOWNLOAD_RESULT
= "RESULT";
37 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
38 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
39 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
40 public static final String EXTRA_FILE_SIZE
= "FILE_SIZE";
41 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
43 private static final String TAG
= "FileDownloader";
45 private NotificationManager mNotificationMngr
;
46 private Looper mServiceLooper
;
47 private ServiceHandler mServiceHandler
;
48 private Account mAccount
;
49 private String mFilePath
;
50 private String mRemotePath
;
51 private int mLastPercent
;
52 private long mTotalDownloadSize
;
53 private long mCurrentDownloadSize
;
54 private Notification mNotification
;
57 * Static map with the files being download and the path to the temporal file were are download
59 private static Map
<String
, String
> mDownloadsInProgress
= Collections
.synchronizedMap(new HashMap
<String
, String
>());
62 * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
64 public static boolean isDownloading(Account account
, String remotePath
) {
65 return (mDownloadsInProgress
.get(buildRemoteName(account
.name
, remotePath
)) != null
);
69 * Builds a key for mDownloadsInProgress from the accountName and remotePath
71 private static String
buildRemoteName(String accountName
, String remotePath
) {
72 return accountName
+ remotePath
;
76 private final class ServiceHandler
extends Handler
{
77 public ServiceHandler(Looper looper
) {
82 public void handleMessage(Message msg
) {
88 public static final String
getSavePath(String accountName
) {
89 File sdCard
= Environment
.getExternalStorageDirectory();
90 return sdCard
.getAbsolutePath() + "/owncloud/" + Uri
.encode(accountName
, "@");
91 // 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
94 public static final String
getTemporalPath(String accountName
) {
95 File sdCard
= Environment
.getExternalStorageDirectory();
96 return sdCard
.getAbsolutePath() + "/owncloud/tmp/" + Uri
.encode(accountName
, "@");
97 // 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
101 public void onCreate() {
103 mNotificationMngr
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
104 HandlerThread thread
= new HandlerThread("FileDownladerThread",
105 Process
.THREAD_PRIORITY_BACKGROUND
);
107 mServiceLooper
= thread
.getLooper();
108 mServiceHandler
= new ServiceHandler(mServiceLooper
);
112 public IBinder
onBind(Intent arg0
) {
117 public int onStartCommand(Intent intent
, int flags
, int startId
) {
118 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
119 !intent
.hasExtra(EXTRA_FILE_PATH
) ||
120 !intent
.hasExtra(EXTRA_REMOTE_PATH
)
122 Log
.e(TAG
, "Not enough information provided in intent");
123 return START_NOT_STICKY
;
125 mAccount
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
126 mFilePath
= intent
.getStringExtra(EXTRA_FILE_PATH
);
127 mRemotePath
= intent
.getStringExtra(EXTRA_REMOTE_PATH
);
128 mTotalDownloadSize
= intent
.getLongExtra(EXTRA_FILE_SIZE
, -1);
129 mCurrentDownloadSize
= mLastPercent
= 0;
131 Message msg
= mServiceHandler
.obtainMessage();
133 mServiceHandler
.sendMessage(msg
);
135 return START_NOT_STICKY
;
139 * Core download method: requests the file to download and stores it.
141 private void downloadFile() {
142 boolean downloadResult
= false
;
144 /// prepare client object to send the request to the ownCloud server
145 WebdavClient wdc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getApplicationContext());
146 wdc
.setDataTransferProgressListener(this);
148 /// download will be in a temporal file
149 File tmpFile
= new File(getTemporalPath(mAccount
.name
) + mFilePath
);
151 /// create status notification to show the download progress
152 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.downloader_download_in_progress_ticker
), System
.currentTimeMillis());
153 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
154 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
155 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, mTotalDownloadSize
== -1);
156 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0, tmpFile
.getName()));
157 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
158 // TODO put something smart in the contentIntent below
159 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
160 mNotificationMngr
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
163 /// perform the download
164 tmpFile
.getParentFile().mkdirs();
165 mDownloadsInProgress
.put(buildRemoteName(mAccount
.name
, mRemotePath
), tmpFile
.getAbsolutePath());
168 if (wdc
.downloadFile(mRemotePath
, tmpFile
)) {
169 newFile
= new File(getSavePath(mAccount
.name
) + mFilePath
);
170 newFile
.getParentFile().mkdirs();
171 boolean moved
= tmpFile
.renameTo(newFile
);
174 ContentValues cv
= new ContentValues();
175 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, newFile
.getAbsolutePath());
176 getContentResolver().update(
177 ProviderTableMeta
.CONTENT_URI
,
179 ProviderTableMeta
.FILE_NAME
+ "=? AND "
180 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?",
182 mFilePath
.substring(mFilePath
.lastIndexOf('/') + 1),
184 downloadResult
= true
;
188 mDownloadsInProgress
.remove(buildRemoteName(mAccount
.name
, mRemotePath
));
193 mNotificationMngr
.cancel(R
.string
.downloader_download_in_progress_ticker
);
194 int tickerId
= (downloadResult
) ? R
.string
.downloader_download_succeeded_ticker
: R
.string
.downloader_download_failed_ticker
;
195 int contentId
= (downloadResult
) ? R
.string
.downloader_download_succeeded_content
: R
.string
.downloader_download_failed_content
;
196 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(tickerId
), System
.currentTimeMillis());
197 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
198 // TODO put something smart in the contentIntent below
199 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
200 finalNotification
.setLatestEventInfo(getApplicationContext(), getString(tickerId
), String
.format(getString(contentId
), tmpFile
.getName()), finalNotification
.contentIntent
);
201 mNotificationMngr
.notify(tickerId
, finalNotification
);
203 sendFinalBroadcast(downloadResult
, (downloadResult
)?newFile
.getAbsolutePath():null
);
207 * Callback method to update the progress bar in the status notification.
210 public void transferProgress(long progressRate
) {
211 mCurrentDownloadSize
+= progressRate
;
212 int percent
= (int)(100.0*((double)mCurrentDownloadSize
)/((double)mTotalDownloadSize
));
213 if (percent
!= mLastPercent
) {
214 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, (int)(100*mCurrentDownloadSize
/mTotalDownloadSize
), mTotalDownloadSize
== -1);
215 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, new File(mFilePath
).getName()));
216 mNotificationMngr
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
219 mLastPercent
= percent
;
224 * Sends a broadcast in order to the interested activities can update their view
226 * @param downloadResult 'True' if the download was successful
227 * @param newFilePath Absolute path to the download file
229 private void sendFinalBroadcast(boolean downloadResult
, String newFilePath
) {
230 Intent end
= new Intent(DOWNLOAD_FINISH_MESSAGE
);
231 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
);
232 end
.putExtra(ACCOUNT_NAME
, mAccount
.name
);
233 end
.putExtra(EXTRA_REMOTE_PATH
, mRemotePath
);
234 if (downloadResult
) {
235 end
.putExtra(EXTRA_FILE_PATH
, newFilePath
);