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