b0dd2b262b6c111deea8d488d5706dcda9664fb4
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / files / services / FileDownloader.java
1 package eu.alefzero.owncloud.files.services;
2
3 import java.io.File;
4 import java.util.Collections;
5 import java.util.HashMap;
6 import java.util.Map;
7
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;
31
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";
40
41 private static final String TAG = "FileDownloader";
42
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;
53
54 /**
55 * Static map with the files being download and the path to the temporal file were are download
56 */
57 private static Map<String, String> mDownloadsInProgress = Collections.synchronizedMap(new HashMap<String, String>());
58
59 /**
60 * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
61 */
62 public static boolean isDownloading(Account account, String remotePath) {
63 return (mDownloadsInProgress.get(buildRemoteName(account.name, remotePath)) != null);
64 }
65
66 /**
67 * Builds a key for mDownloadsInProgress from the accountName and remotePath
68 */
69 private static String buildRemoteName(String accountName, String remotePath) {
70 return accountName + remotePath;
71 }
72
73
74 private final class ServiceHandler extends Handler {
75 public ServiceHandler(Looper looper) {
76 super(looper);
77 }
78
79 @Override
80 public void handleMessage(Message msg) {
81 downloadFile();
82 stopSelf(msg.arg1);
83 }
84 }
85
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
90 }
91
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
96 }
97
98 @Override
99 public void onCreate() {
100 super.onCreate();
101 mNotificationMngr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
102 HandlerThread thread = new HandlerThread("FileDownladerThread",
103 Process.THREAD_PRIORITY_BACKGROUND);
104 thread.start();
105 mServiceLooper = thread.getLooper();
106 mServiceHandler = new ServiceHandler(mServiceLooper);
107 }
108
109 @Override
110 public IBinder onBind(Intent arg0) {
111 return null;
112 }
113
114 @Override
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)
119 ) {
120 Log.e(TAG, "Not enough information provided in intent");
121 return START_NOT_STICKY;
122 }
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;
128
129 Message msg = mServiceHandler.obtainMessage();
130 msg.arg1 = startId;
131 mServiceHandler.sendMessage(msg);
132
133 return START_NOT_STICKY;
134 }
135
136 /**
137 * Core download method: requests the file to download and stores it.
138 */
139 private void downloadFile() {
140 boolean downloadResult = false;
141
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;
147 try {
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);
153 return;
154 }
155 wdc.setCredentials(username, password);
156 wdc.allowSelfsignedCertificates();
157 wdc.setDataTransferProgressListener(this);
158
159
160 /// download will be in a temporal file
161 File tmpFile = new File(getTemporalPath(mAccount.name) + mFilePath);
162
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);
173
174
175 /// perform the download
176 tmpFile.getParentFile().mkdirs();
177 mDownloadsInProgress.put(buildRemoteName(mAccount.name, mRemotePath), tmpFile.getAbsolutePath());
178 File newFile = null;
179 try {
180 if (wdc.downloadFile(mRemotePath, tmpFile)) {
181 newFile = new File(getSavePath(mAccount.name) + mFilePath);
182 newFile.getParentFile().mkdirs();
183 boolean moved = tmpFile.renameTo(newFile);
184
185 if (moved) {
186 ContentValues cv = new ContentValues();
187 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, newFile.getAbsolutePath());
188 getContentResolver().update(
189 ProviderTableMeta.CONTENT_URI,
190 cv,
191 ProviderTableMeta.FILE_NAME + "=? AND "
192 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
193 new String[] {
194 mFilePath.substring(mFilePath.lastIndexOf('/') + 1),
195 mAccount.name });
196 downloadResult = true;
197 }
198 }
199 } finally {
200 mDownloadsInProgress.remove(buildRemoteName(mAccount.name, mRemotePath));
201 }
202
203
204 /// notify result
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);
214
215 sendFinalBroadcast(downloadResult, (downloadResult)?newFile.getAbsolutePath():null);
216 }
217
218 /**
219 * Callback method to update the progress bar in the status notification.
220 */
221 @Override
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);
229 }
230
231 mLastPercent = percent;
232 }
233
234
235 /**
236 * Sends a broadcast in order to the interested activities can update their view
237 *
238 * @param downloadResult 'True' if the download was successful
239 * @param newFilePath Absolute path to the download file
240 */
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);
248 }
249 sendBroadcast(end);
250 }
251
252 }