1 package eu
.alefzero
.owncloud
.files
.services
;
4 import java
.util
.Collections
;
5 import java
.util
.HashMap
;
8 import android
.accounts
.Account
;
9 import android
.accounts
.AccountManager
;
10 import android
.app
.Notification
;
11 import android
.app
.NotificationManager
;
12 import android
.app
.PendingIntent
;
13 import android
.app
.Service
;
14 import android
.content
.ContentValues
;
15 import android
.content
.Intent
;
16 import android
.net
.Uri
;
17 import android
.os
.Environment
;
18 import android
.os
.Handler
;
19 import android
.os
.HandlerThread
;
20 import android
.os
.IBinder
;
21 import android
.os
.Looper
;
22 import android
.os
.Message
;
23 import android
.os
.Process
;
24 import android
.util
.Log
;
25 import android
.widget
.RemoteViews
;
26 import eu
.alefzero
.owncloud
.R
;
27 import eu
.alefzero
.owncloud
.authenticator
.AccountAuthenticator
;
28 import eu
.alefzero
.owncloud
.db
.ProviderMeta
.ProviderTableMeta
;
29 import eu
.alefzero
.owncloud
.files
.interfaces
.OnDatatransferProgressListener
;
30 import eu
.alefzero
.webdav
.WebdavClient
;
32 public class FileDownloader
extends Service
implements OnDatatransferProgressListener
{
33 public static final String DOWNLOAD_FINISH_MESSAGE
= "DOWNLOAD_FINISH";
34 public static final String EXTRA_DOWNLOAD_RESULT
= "RESULT";
35 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
36 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
37 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
38 public static final String EXTRA_FILE_SIZE
= "FILE_SIZE";
39 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
41 private static final String TAG
= "FileDownloader";
43 private NotificationManager mNotificationMngr
;
44 private Looper mServiceLooper
;
45 private ServiceHandler mServiceHandler
;
46 private Account mAccount
;
47 private String mFilePath
;
48 private String mRemotePath
;
49 private int mLastPercent
;
50 private long mTotalDownloadSize
;
51 private long mCurrentDownloadSize
;
52 private Notification mNotification
;
55 * Static map with the files being download and the path to the temporal file were are download
57 private static Map
<String
, String
> mDownloadsInProgress
= Collections
.synchronizedMap(new HashMap
<String
, String
>());
60 * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
62 public static boolean isDownloading(Account account
, String remotePath
) {
63 return (mDownloadsInProgress
.get(buildRemoteName(account
.name
, remotePath
)) != null
);
67 * Builds a key for mDownloadsInProgress from the accountName and remotePath
69 private static String
buildRemoteName(String accountName
, String remotePath
) {
70 return accountName
+ remotePath
;
74 private final class ServiceHandler
extends Handler
{
75 public ServiceHandler(Looper looper
) {
80 public void handleMessage(Message msg
) {
86 public static final String
getSavePath(String accountName
) {
87 File sdCard
= Environment
.getExternalStorageDirectory();
88 return sdCard
.getAbsolutePath() + "/owncloud/" + Uri
.encode(accountName
, "@");
89 // 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
92 public static final String
getTemporalPath(String accountName
) {
93 File sdCard
= Environment
.getExternalStorageDirectory();
94 return sdCard
.getAbsolutePath() + "/owncloud/tmp/" + Uri
.encode(accountName
, "@");
95 // 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
99 public void onCreate() {
101 mNotificationMngr
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
102 HandlerThread thread
= new HandlerThread("FileDownladerThread",
103 Process
.THREAD_PRIORITY_BACKGROUND
);
105 mServiceLooper
= thread
.getLooper();
106 mServiceHandler
= new ServiceHandler(mServiceLooper
);
110 public IBinder
onBind(Intent arg0
) {
115 public int onStartCommand(Intent intent
, int flags
, int startId
) {
116 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
117 !intent
.hasExtra(EXTRA_FILE_PATH
) ||
118 !intent
.hasExtra(EXTRA_REMOTE_PATH
)
120 Log
.e(TAG
, "Not enough information provided in intent");
121 return START_NOT_STICKY
;
123 mAccount
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
124 mFilePath
= intent
.getStringExtra(EXTRA_FILE_PATH
);
125 mRemotePath
= intent
.getStringExtra(EXTRA_REMOTE_PATH
);
126 mTotalDownloadSize
= intent
.getLongExtra(EXTRA_FILE_SIZE
, -1);
127 mCurrentDownloadSize
= mLastPercent
= 0;
129 Message msg
= mServiceHandler
.obtainMessage();
131 mServiceHandler
.sendMessage(msg
);
133 return START_NOT_STICKY
;
137 * Core download method: requests the file to download and stores it.
139 private void downloadFile() {
140 boolean downloadResult
= false
;
142 /// prepare client object to send the request to the ownCloud server
143 AccountManager am
= (AccountManager
) getSystemService(ACCOUNT_SERVICE
);
144 WebdavClient wdc
= new WebdavClient(mAccount
, getApplicationContext());
145 String username
= mAccount
.name
.split("@")[0];
146 String password
= null
;
148 password
= am
.blockingGetAuthToken(mAccount
,
149 AccountAuthenticator
.AUTH_TOKEN_TYPE
, true
);
150 } catch (Exception e
) {
151 Log
.e(TAG
, "Access to account credentials failed", e
);
152 sendFinalBroadcast(downloadResult
, null
);
155 wdc
.setCredentials(username
, password
);
156 wdc
.allowSelfsignedCertificates();
157 wdc
.setDataTransferProgressListener(this);
160 /// download will be in a temporal file
161 File tmpFile
= new File(getTemporalPath(mAccount
.name
) + mFilePath
);
163 /// create status notification to show the download progress
164 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.downloader_download_in_progress_ticker
), System
.currentTimeMillis());
165 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
166 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
167 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, mTotalDownloadSize
== -1);
168 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0, tmpFile
.getName()));
169 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
170 // TODO put something smart in the contentIntent below
171 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
172 mNotificationMngr
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
175 /// perform the download
176 tmpFile
.getParentFile().mkdirs();
177 mDownloadsInProgress
.put(buildRemoteName(mAccount
.name
, mRemotePath
), tmpFile
.getAbsolutePath());
180 if (wdc
.downloadFile(mRemotePath
, tmpFile
)) {
181 newFile
= new File(getSavePath(mAccount
.name
) + mFilePath
);
182 newFile
.getParentFile().mkdirs();
183 boolean moved
= tmpFile
.renameTo(newFile
);
186 ContentValues cv
= new ContentValues();
187 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, newFile
.getAbsolutePath());
188 getContentResolver().update(
189 ProviderTableMeta
.CONTENT_URI
,
191 ProviderTableMeta
.FILE_NAME
+ "=? AND "
192 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?",
194 mFilePath
.substring(mFilePath
.lastIndexOf('/') + 1),
196 downloadResult
= true
;
200 mDownloadsInProgress
.remove(buildRemoteName(mAccount
.name
, mRemotePath
));
205 mNotificationMngr
.cancel(R
.string
.downloader_download_in_progress_ticker
);
206 int tickerId
= (downloadResult
) ? R
.string
.downloader_download_succeeded_ticker
: R
.string
.downloader_download_failed_ticker
;
207 int contentId
= (downloadResult
) ? R
.string
.downloader_download_succeeded_content
: R
.string
.downloader_download_failed_content
;
208 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(tickerId
), System
.currentTimeMillis());
209 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
210 // TODO put something smart in the contentIntent below
211 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
212 finalNotification
.setLatestEventInfo(getApplicationContext(), getString(tickerId
), String
.format(getString(contentId
), tmpFile
.getName()), finalNotification
.contentIntent
);
213 mNotificationMngr
.notify(tickerId
, finalNotification
);
215 sendFinalBroadcast(downloadResult
, (downloadResult
)?newFile
.getAbsolutePath():null
);
219 * Callback method to update the progress bar in the status notification.
222 public void transferProgress(long progressRate
) {
223 mCurrentDownloadSize
+= progressRate
;
224 int percent
= (int)(100.0*((double)mCurrentDownloadSize
)/((double)mTotalDownloadSize
));
225 if (percent
!= mLastPercent
) {
226 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, (int)(100*mCurrentDownloadSize
/mTotalDownloadSize
), mTotalDownloadSize
== -1);
227 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, new File(mFilePath
).getName()));
228 mNotificationMngr
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
231 mLastPercent
= percent
;
236 * Sends a broadcast in order to the interested activities can update their view
238 * @param downloadResult 'True' if the download was successful
239 * @param newFilePath Absolute path to the download file
241 private void sendFinalBroadcast(boolean downloadResult
, String newFilePath
) {
242 Intent end
= new Intent(DOWNLOAD_FINISH_MESSAGE
);
243 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
);
244 end
.putExtra(ACCOUNT_NAME
, mAccount
.name
);
245 end
.putExtra(EXTRA_REMOTE_PATH
, mRemotePath
);
246 if (downloadResult
) {
247 end
.putExtra(EXTRA_FILE_PATH
, newFilePath
);