Fixed null pointer in connection check
[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
12 import com.owncloud.android.network.OwnCloudClientUtils;
13
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;
34
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";
43
44 private static final String TAG = "FileDownloader";
45
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;
56
57 /**
58 * Static map with the files being download and the path to the temporal file were are download
59 */
60 private static Map<String, String> mDownloadsInProgress = Collections.synchronizedMap(new HashMap<String, String>());
61
62 /**
63 * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
64 */
65 public static boolean isDownloading(Account account, String remotePath) {
66 return (mDownloadsInProgress.get(buildRemoteName(account.name, remotePath)) != null);
67 }
68
69 /**
70 * Builds a key for mDownloadsInProgress from the accountName and remotePath
71 */
72 private static String buildRemoteName(String accountName, String remotePath) {
73 return accountName + remotePath;
74 }
75
76
77 private final class ServiceHandler extends Handler {
78 public ServiceHandler(Looper looper) {
79 super(looper);
80 }
81
82 @Override
83 public void handleMessage(Message msg) {
84 downloadFile();
85 stopSelf(msg.arg1);
86 }
87 }
88
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
93 }
94
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
99 }
100
101 @Override
102 public void onCreate() {
103 super.onCreate();
104 mNotificationMngr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
105 HandlerThread thread = new HandlerThread("FileDownladerThread",
106 Process.THREAD_PRIORITY_BACKGROUND);
107 thread.start();
108 mServiceLooper = thread.getLooper();
109 mServiceHandler = new ServiceHandler(mServiceLooper);
110 }
111
112 @Override
113 public IBinder onBind(Intent arg0) {
114 return null;
115 }
116
117 @Override
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)
122 ) {
123 Log.e(TAG, "Not enough information provided in intent");
124 return START_NOT_STICKY;
125 }
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;
131
132 Message msg = mServiceHandler.obtainMessage();
133 msg.arg1 = startId;
134 mServiceHandler.sendMessage(msg);
135
136 return START_NOT_STICKY;
137 }
138
139 /**
140 * Core download method: requests the file to download and stores it.
141 */
142 private void downloadFile() {
143 boolean downloadResult = false;
144
145 /// prepare client object to send the request to the ownCloud server
146 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
147 wdc.setDataTransferProgressListener(this);
148
149 /// download will be in a temporal file
150 File tmpFile = new File(getTemporalPath(mAccount.name) + mFilePath);
151
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);
162
163
164 /// perform the download
165 tmpFile.getParentFile().mkdirs();
166 mDownloadsInProgress.put(buildRemoteName(mAccount.name, mRemotePath), tmpFile.getAbsolutePath());
167 File newFile = null;
168 try {
169 if (wdc.downloadFile(mRemotePath, tmpFile)) {
170 newFile = new File(getSavePath(mAccount.name) + mFilePath);
171 newFile.getParentFile().mkdirs();
172 boolean moved = tmpFile.renameTo(newFile);
173
174 if (moved) {
175 ContentValues cv = new ContentValues();
176 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, newFile.getAbsolutePath());
177 getContentResolver().update(
178 ProviderTableMeta.CONTENT_URI,
179 cv,
180 ProviderTableMeta.FILE_NAME + "=? AND "
181 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
182 new String[] {
183 mFilePath.substring(mFilePath.lastIndexOf('/') + 1),
184 mAccount.name });
185 downloadResult = true;
186 }
187 }
188 } finally {
189 mDownloadsInProgress.remove(buildRemoteName(mAccount.name, mRemotePath));
190 }
191
192
193 /// notify result
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);
203
204 sendFinalBroadcast(downloadResult, (downloadResult)?newFile.getAbsolutePath():null);
205 }
206
207 /**
208 * Callback method to update the progress bar in the status notification.
209 */
210 @Override
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);
218 }
219
220 mLastPercent = percent;
221 }
222
223
224 /**
225 * Sends a broadcast in order to the interested activities can update their view
226 *
227 * @param downloadResult 'True' if the download was successful
228 * @param newFilePath Absolute path to the download file
229 */
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);
237 }
238 sendBroadcast(end);
239 }
240
241 }