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
;
12 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
14 import android
.accounts
.Account
;
15 import android
.accounts
.AccountManager
;
16 import android
.app
.Notification
;
17 import android
.app
.NotificationManager
;
18 import android
.app
.PendingIntent
;
19 import android
.app
.Service
;
20 import android
.content
.ContentValues
;
21 import android
.content
.Intent
;
22 import android
.net
.Uri
;
23 import android
.os
.Environment
;
24 import android
.os
.Handler
;
25 import android
.os
.HandlerThread
;
26 import android
.os
.IBinder
;
27 import android
.os
.Looper
;
28 import android
.os
.Message
;
29 import android
.os
.Process
;
30 import android
.util
.Log
;
31 import android
.widget
.RemoteViews
;
32 import com
.owncloud
.android
.R
;
33 import eu
.alefzero
.webdav
.WebdavClient
;
35 public class FileDownloader
extends Service
implements OnDatatransferProgressListener
{
36 public static final String DOWNLOAD_FINISH_MESSAGE
= "DOWNLOAD_FINISH";
37 public static final String EXTRA_DOWNLOAD_RESULT
= "RESULT";
38 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
39 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
40 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
41 public static final String EXTRA_FILE_SIZE
= "FILE_SIZE";
42 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
44 private static final String TAG
= "FileDownloader";
46 private NotificationManager mNotificationMngr
;
47 private Looper mServiceLooper
;
48 private ServiceHandler mServiceHandler
;
49 private Account mAccount
;
50 private String mFilePath
;
51 private String mRemotePath
;
52 private int mLastPercent
;
53 private long mTotalDownloadSize
;
54 private long mCurrentDownloadSize
;
55 private Notification mNotification
;
58 * Static map with the files being download and the path to the temporal file were are download
60 private static Map
<String
, String
> mDownloadsInProgress
= Collections
.synchronizedMap(new HashMap
<String
, String
>());
63 * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
65 public static boolean isDownloading(Account account
, String remotePath
) {
66 return (mDownloadsInProgress
.get(buildRemoteName(account
.name
, remotePath
)) != null
);
70 * Builds a key for mDownloadsInProgress from the accountName and remotePath
72 private static String
buildRemoteName(String accountName
, String remotePath
) {
73 return accountName
+ remotePath
;
77 private final class ServiceHandler
extends Handler
{
78 public ServiceHandler(Looper looper
) {
83 public void handleMessage(Message msg
) {
89 public static final String
getSavePath(String accountName
) {
90 File sdCard
= Environment
.getExternalStorageDirectory();
91 return sdCard
.getAbsolutePath() + "/owncloud/" + Uri
.encode(accountName
, "@");
92 // 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
95 public static final String
getTemporalPath(String accountName
) {
96 File sdCard
= Environment
.getExternalStorageDirectory();
97 return sdCard
.getAbsolutePath() + "/owncloud/tmp/" + Uri
.encode(accountName
, "@");
98 // 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
102 public void onCreate() {
104 mNotificationMngr
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
105 HandlerThread thread
= new HandlerThread("FileDownladerThread",
106 Process
.THREAD_PRIORITY_BACKGROUND
);
108 mServiceLooper
= thread
.getLooper();
109 mServiceHandler
= new ServiceHandler(mServiceLooper
);
113 public IBinder
onBind(Intent arg0
) {
118 public int onStartCommand(Intent intent
, int flags
, int startId
) {
119 if ( !intent
.hasExtra(EXTRA_ACCOUNT
) ||
120 !intent
.hasExtra(EXTRA_FILE_PATH
) ||
121 !intent
.hasExtra(EXTRA_REMOTE_PATH
)
123 Log
.e(TAG
, "Not enough information provided in intent");
124 return START_NOT_STICKY
;
126 mAccount
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
127 mFilePath
= intent
.getStringExtra(EXTRA_FILE_PATH
);
128 mRemotePath
= intent
.getStringExtra(EXTRA_REMOTE_PATH
);
129 mTotalDownloadSize
= intent
.getLongExtra(EXTRA_FILE_SIZE
, -1);
130 mCurrentDownloadSize
= mLastPercent
= 0;
132 Message msg
= mServiceHandler
.obtainMessage();
134 mServiceHandler
.sendMessage(msg
);
136 return START_NOT_STICKY
;
140 * Core download method: requests the file to download and stores it.
142 private void downloadFile() {
143 boolean downloadResult
= false
;
145 /// prepare client object to send the request to the ownCloud server
146 WebdavClient wdc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getApplicationContext());
147 wdc
.setDataTransferProgressListener(this);
149 /// download will be in a temporal file
150 File tmpFile
= new File(getTemporalPath(mAccount
.name
) + mFilePath
);
152 /// create status notification to show the download progress
153 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.downloader_download_in_progress_ticker
), System
.currentTimeMillis());
154 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
155 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
156 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, mTotalDownloadSize
== -1);
157 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0, tmpFile
.getName()));
158 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
159 // TODO put something smart in the contentIntent below
160 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
161 mNotificationMngr
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
164 /// perform the download
165 tmpFile
.getParentFile().mkdirs();
166 mDownloadsInProgress
.put(buildRemoteName(mAccount
.name
, mRemotePath
), tmpFile
.getAbsolutePath());
169 if (wdc
.downloadFile(mRemotePath
, tmpFile
)) {
170 newFile
= new File(getSavePath(mAccount
.name
) + mFilePath
);
171 newFile
.getParentFile().mkdirs();
172 boolean moved
= tmpFile
.renameTo(newFile
);
175 ContentValues cv
= new ContentValues();
176 cv
.put(ProviderTableMeta
.FILE_STORAGE_PATH
, newFile
.getAbsolutePath());
177 getContentResolver().update(
178 ProviderTableMeta
.CONTENT_URI
,
180 ProviderTableMeta
.FILE_NAME
+ "=? AND "
181 + ProviderTableMeta
.FILE_ACCOUNT_OWNER
+ "=?",
183 mFilePath
.substring(mFilePath
.lastIndexOf('/') + 1),
185 downloadResult
= true
;
189 mDownloadsInProgress
.remove(buildRemoteName(mAccount
.name
, mRemotePath
));
194 mNotificationMngr
.cancel(R
.string
.downloader_download_in_progress_ticker
);
195 int tickerId
= (downloadResult
) ? R
.string
.downloader_download_succeeded_ticker
: R
.string
.downloader_download_failed_ticker
;
196 int contentId
= (downloadResult
) ? R
.string
.downloader_download_succeeded_content
: R
.string
.downloader_download_failed_content
;
197 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(tickerId
), System
.currentTimeMillis());
198 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
199 // TODO put something smart in the contentIntent below
200 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
201 finalNotification
.setLatestEventInfo(getApplicationContext(), getString(tickerId
), String
.format(getString(contentId
), tmpFile
.getName()), finalNotification
.contentIntent
);
202 mNotificationMngr
.notify(tickerId
, finalNotification
);
204 sendFinalBroadcast(downloadResult
, (downloadResult
)?newFile
.getAbsolutePath():null
);
208 * Callback method to update the progress bar in the status notification.
211 public void transferProgress(long progressRate
) {
212 mCurrentDownloadSize
+= progressRate
;
213 int percent
= (int)(100.0*((double)mCurrentDownloadSize
)/((double)mTotalDownloadSize
));
214 if (percent
!= mLastPercent
) {
215 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, (int)(100*mCurrentDownloadSize
/mTotalDownloadSize
), mTotalDownloadSize
== -1);
216 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, new File(mFilePath
).getName()));
217 mNotificationMngr
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotification
);
220 mLastPercent
= percent
;
225 * Sends a broadcast in order to the interested activities can update their view
227 * @param downloadResult 'True' if the download was successful
228 * @param newFilePath Absolute path to the download file
230 private void sendFinalBroadcast(boolean downloadResult
, String newFilePath
) {
231 Intent end
= new Intent(DOWNLOAD_FINISH_MESSAGE
);
232 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
);
233 end
.putExtra(ACCOUNT_NAME
, mAccount
.name
);
234 end
.putExtra(EXTRA_REMOTE_PATH
, mRemotePath
);
235 if (downloadResult
) {
236 end
.putExtra(EXTRA_FILE_PATH
, newFilePath
);