3ee316fafe477b432d30c170909ca34a0c309d92
[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.io.IOException;
5 import java.util.Collections;
6 import java.util.HashMap;
7 import java.util.Map;
8
9 import android.accounts.Account;
10 import android.accounts.AccountManager;
11 import android.accounts.AuthenticatorException;
12 import android.accounts.OperationCanceledException;
13 import android.app.Notification;
14 import android.app.NotificationManager;
15 import android.app.PendingIntent;
16 import android.app.Service;
17 import android.content.ContentValues;
18 import android.content.Intent;
19 import android.os.Environment;
20 import android.os.Handler;
21 import android.os.HandlerThread;
22 import android.os.IBinder;
23 import android.os.Looper;
24 import android.os.Message;
25 import android.os.Process;
26 import android.util.Log;
27 import android.util.LogPrinter;
28 import android.widget.RemoteViews;
29 import android.widget.Toast;
30 import eu.alefzero.owncloud.R;
31 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
32 import eu.alefzero.owncloud.db.ProviderMeta.ProviderTableMeta;
33 import eu.alefzero.owncloud.files.interfaces.OnDatatransferProgressListener;
34 import eu.alefzero.owncloud.syncadapter.FileSyncService;
35 import eu.alefzero.webdav.WebdavClient;
36
37 public class FileDownloader extends Service implements OnDatatransferProgressListener {
38 public static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
39 public static final String EXTRA_DOWNLOAD_RESULT = "RESULT";
40 public static final String EXTRA_ACCOUNT = "ACCOUNT";
41 public static final String EXTRA_FILE_PATH = "FILE_PATH";
42 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
43 public static final String EXTRA_FILE_SIZE = "FILE_SIZE";
44 public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
45 private static final String TAG = "FileDownloader";
46
47 private NotificationManager mNotificationMngr;
48 private Looper mServiceLooper;
49 private ServiceHandler mServiceHandler;
50 private Account mAccount;
51 private String mFilePath;
52 private String mRemotePath;
53 private int mLastPercent;
54 private long mTotalDownloadSize;
55 private long mCurrentDownloadSize;
56 private Notification mNotification;
57
58 /**
59 * Static map with the files being download and the path to the temporal file were are download
60 */
61 private static Map<String, String> mDownloadsInProgress = Collections.synchronizedMap(new HashMap<String, String>());
62
63 /**
64 * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
65 */
66 public static boolean isDownloading(Account account, String remotePath) {
67 return (mDownloadsInProgress.get(buildRemoteName(account.name, remotePath)) != null);
68 }
69
70 /**
71 * Builds a key for mDownloadsInProgress from the accountName and remotePath
72 */
73 private static String buildRemoteName(String accountName, String remotePath) {
74 return accountName + remotePath;
75 }
76
77
78 private final class ServiceHandler extends Handler {
79 public ServiceHandler(Looper looper) {
80 super(looper);
81 }
82
83 @Override
84 public void handleMessage(Message msg) {
85 downloadFile();
86 stopSelf(msg.arg1);
87 }
88 }
89
90 public static final String getSavePath() {
91 File sdCard = Environment.getExternalStorageDirectory();
92 return sdCard.getAbsolutePath() + "/owncloud/";
93 }
94
95 public static final String getTemporalPath() {
96 File sdCard = Environment.getExternalStorageDirectory();
97 return sdCard.getAbsolutePath() + "/owncloud.tmp/";
98 }
99
100 @Override
101 public void onCreate() {
102 super.onCreate();
103 mNotificationMngr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
104 HandlerThread thread = new HandlerThread("FileDownladerThread",
105 Process.THREAD_PRIORITY_BACKGROUND);
106 thread.start();
107 mServiceLooper = thread.getLooper();
108 mServiceHandler = new ServiceHandler(mServiceLooper);
109 }
110
111 @Override
112 public IBinder onBind(Intent arg0) {
113 return null;
114 }
115
116 @Override
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)
121 ) {
122 Log.e(TAG, "Not enough information provided in intent");
123 return START_STICKY;
124 }
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;
130
131 Message msg = mServiceHandler.obtainMessage();
132 msg.arg1 = startId;
133 mServiceHandler.sendMessage(msg);
134
135 return START_NOT_STICKY;
136 }
137
138 void downloadFile() {
139 boolean downloadResult = false;
140
141 /// prepare client object to send the request to the ownCloud server
142 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
143 WebdavClient wdc = new WebdavClient(mAccount, getApplicationContext());
144 String username = mAccount.name.split("@")[0];
145 String password = null;
146 try {
147 password = am.blockingGetAuthToken(mAccount,
148 AccountAuthenticator.AUTH_TOKEN_TYPE, true);
149 } catch (Exception e) {
150 Log.e(TAG, "Access to account credentials failed", e);
151 // TODO - check if that log prints the stack trace
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 // dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
171 // BUT an empty Intent is not a very elegant solution; something smart should happen when a user 'clicks' on a download in the notification bar
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 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 mDownloadsInProgress.remove(buildRemoteName(mAccount.name, mRemotePath));
200
201
202 /// notify result
203 mNotificationMngr.cancel(R.string.downloader_download_in_progress_ticker);
204 int tickerId = (downloadResult) ? R.string.downloader_download_succeed_ticker : R.string.downloader_download_failed_ticker;
205 int contentId = (downloadResult) ? R.string.downloader_download_succeed_content : R.string.downloader_download_failed_content;
206 Notification finalNotification = new Notification(R.drawable.icon, getString(tickerId), System.currentTimeMillis());
207 finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
208 // dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
209 // BUT an empty Intent is not a very elegant solution; something smart should happen when a user 'clicks' on a download in the notification bar
210 finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
211 finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), tmpFile.getName()), finalNotification.contentIntent);
212 mNotificationMngr.notify(tickerId, finalNotification);
213
214 sendFinalBroadcast(downloadResult, (downloadResult)?newFile.getAbsolutePath():null);
215 }
216
217
218 @Override
219 public void transferProgress(long progressRate) {
220 mCurrentDownloadSize += progressRate;
221 int percent = (int)(100.0*((double)mCurrentDownloadSize)/((double)mTotalDownloadSize));
222 if (percent != mLastPercent) {
223 mNotification.contentView.setProgressBar(R.id.status_progress, 100, (int)(100*mCurrentDownloadSize/mTotalDownloadSize), mTotalDownloadSize == -1);
224 mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), percent, new File(mFilePath).getName()));
225 mNotificationMngr.notify(R.string.downloader_download_in_progress_ticker, mNotification);
226 }
227
228 mLastPercent = percent;
229 }
230
231
232 /**
233 * Sends a broadcast in order to the interested activities can update their view
234 *
235 * @param downloadResult 'True' if the download was successful
236 * @param newFilePath Absolute path to the download file
237 */
238 private void sendFinalBroadcast(boolean downloadResult, String newFilePath) {
239 Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
240 end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult);
241 end.putExtra(ACCOUNT_NAME, mAccount.name);
242 end.putExtra(EXTRA_REMOTE_PATH, mRemotePath);
243 if (downloadResult) {
244 end.putExtra(EXTRA_FILE_PATH, newFilePath);
245 }
246 sendBroadcast(end);
247 }
248
249 }