Fixing rare crashes in the login page
[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 eu.alefzero.webdav.OnDatatransferProgressListener;
11 import com.owncloud.android.utils.OwnCloudClientUtils;
12
13 import android.accounts.Account;
14 import android.accounts.AccountManager;
15 import android.app.Notification;
16 import android.app.NotificationManager;
17 import android.app.PendingIntent;
18 import android.app.Service;
19 import android.content.ContentValues;
20 import android.content.Intent;
21 import android.net.Uri;
22 import android.os.Environment;
23 import android.os.Handler;
24 import android.os.HandlerThread;
25 import android.os.IBinder;
26 import android.os.Looper;
27 import android.os.Message;
28 import android.os.Process;
29 import android.util.Log;
30 import android.widget.RemoteViews;
31 import com.owncloud.android.R;
32 import eu.alefzero.webdav.WebdavClient;
33
34 public class FileDownloader extends Service implements OnDatatransferProgressListener {
35 public static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
36 public static final String EXTRA_DOWNLOAD_RESULT = "RESULT";
37 public static final String EXTRA_ACCOUNT = "ACCOUNT";
38 public static final String EXTRA_FILE_PATH = "FILE_PATH";
39 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
40 public static final String EXTRA_FILE_SIZE = "FILE_SIZE";
41 public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
42
43 private static final String TAG = "FileDownloader";
44
45 private NotificationManager mNotificationMngr;
46 private Looper mServiceLooper;
47 private ServiceHandler mServiceHandler;
48 private Account mAccount;
49 private String mFilePath;
50 private String mRemotePath;
51 private int mLastPercent;
52 private long mTotalDownloadSize;
53 private long mCurrentDownloadSize;
54 private Notification mNotification;
55
56 /**
57 * Static map with the files being download and the path to the temporal file were are download
58 */
59 private static Map<String, String> mDownloadsInProgress = Collections.synchronizedMap(new HashMap<String, String>());
60
61 /**
62 * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
63 */
64 public static boolean isDownloading(Account account, String remotePath) {
65 return (mDownloadsInProgress.get(buildRemoteName(account.name, remotePath)) != null);
66 }
67
68 /**
69 * Builds a key for mDownloadsInProgress from the accountName and remotePath
70 */
71 private static String buildRemoteName(String accountName, String remotePath) {
72 return accountName + remotePath;
73 }
74
75
76 private final class ServiceHandler extends Handler {
77 public ServiceHandler(Looper looper) {
78 super(looper);
79 }
80
81 @Override
82 public void handleMessage(Message msg) {
83 downloadFile();
84 stopSelf(msg.arg1);
85 }
86 }
87
88 public static final String getSavePath(String accountName) {
89 File sdCard = Environment.getExternalStorageDirectory();
90 return sdCard.getAbsolutePath() + "/owncloud/" + Uri.encode(accountName, "@");
91 // 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 }
93
94 public static final String getTemporalPath(String accountName) {
95 File sdCard = Environment.getExternalStorageDirectory();
96 return sdCard.getAbsolutePath() + "/owncloud/tmp/" + Uri.encode(accountName, "@");
97 // 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
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_NOT_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 /**
139 * Core download method: requests the file to download and stores it.
140 */
141 private void downloadFile() {
142 boolean downloadResult = false;
143
144 /// prepare client object to send the request to the ownCloud server
145 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
146 wdc.setDataTransferProgressListener(this);
147
148 /// download will be in a temporal file
149 File tmpFile = new File(getTemporalPath(mAccount.name) + mFilePath);
150
151 /// create status notification to show the download progress
152 mNotification = new Notification(R.drawable.icon, getString(R.string.downloader_download_in_progress_ticker), System.currentTimeMillis());
153 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
154 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
155 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, mTotalDownloadSize == -1);
156 mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), 0, tmpFile.getName()));
157 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
158 // TODO put something smart in the contentIntent below
159 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
160 mNotificationMngr.notify(R.string.downloader_download_in_progress_ticker, mNotification);
161
162
163 /// perform the download
164 tmpFile.getParentFile().mkdirs();
165 mDownloadsInProgress.put(buildRemoteName(mAccount.name, mRemotePath), tmpFile.getAbsolutePath());
166 File newFile = null;
167 try {
168 if (wdc.downloadFile(mRemotePath, tmpFile)) {
169 newFile = new File(getSavePath(mAccount.name) + mFilePath);
170 newFile.getParentFile().mkdirs();
171 boolean moved = tmpFile.renameTo(newFile);
172
173 if (moved) {
174 ContentValues cv = new ContentValues();
175 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, newFile.getAbsolutePath());
176 getContentResolver().update(
177 ProviderTableMeta.CONTENT_URI,
178 cv,
179 ProviderTableMeta.FILE_NAME + "=? AND "
180 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
181 new String[] {
182 mFilePath.substring(mFilePath.lastIndexOf('/') + 1),
183 mAccount.name });
184 downloadResult = true;
185 }
186 }
187 } finally {
188 mDownloadsInProgress.remove(buildRemoteName(mAccount.name, mRemotePath));
189 }
190
191
192 /// notify result
193 mNotificationMngr.cancel(R.string.downloader_download_in_progress_ticker);
194 int tickerId = (downloadResult) ? R.string.downloader_download_succeeded_ticker : R.string.downloader_download_failed_ticker;
195 int contentId = (downloadResult) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;
196 Notification finalNotification = new Notification(R.drawable.icon, getString(tickerId), System.currentTimeMillis());
197 finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
198 // TODO put something smart in the contentIntent below
199 finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
200 finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), tmpFile.getName()), finalNotification.contentIntent);
201 mNotificationMngr.notify(tickerId, finalNotification);
202
203 sendFinalBroadcast(downloadResult, (downloadResult)?newFile.getAbsolutePath():null);
204 }
205
206 /**
207 * Callback method to update the progress bar in the status notification.
208 */
209 @Override
210 public void transferProgress(long progressRate) {
211 mCurrentDownloadSize += progressRate;
212 int percent = (int)(100.0*((double)mCurrentDownloadSize)/((double)mTotalDownloadSize));
213 if (percent != mLastPercent) {
214 mNotification.contentView.setProgressBar(R.id.status_progress, 100, (int)(100*mCurrentDownloadSize/mTotalDownloadSize), mTotalDownloadSize == -1);
215 mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), percent, new File(mFilePath).getName()));
216 mNotificationMngr.notify(R.string.downloader_download_in_progress_ticker, mNotification);
217 }
218
219 mLastPercent = percent;
220 }
221
222
223 /**
224 * Sends a broadcast in order to the interested activities can update their view
225 *
226 * @param downloadResult 'True' if the download was successful
227 * @param newFilePath Absolute path to the download file
228 */
229 private void sendFinalBroadcast(boolean downloadResult, String newFilePath) {
230 Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
231 end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult);
232 end.putExtra(ACCOUNT_NAME, mAccount.name);
233 end.putExtra(EXTRA_REMOTE_PATH, mRemotePath);
234 if (downloadResult) {
235 end.putExtra(EXTRA_FILE_PATH, newFilePath);
236 }
237 sendBroadcast(end);
238 }
239
240 }