removing some obvious warnings as first step to -Werror
[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.db.ProviderMeta.ProviderTableMeta;
9 import eu.alefzero.webdav.OnDatatransferProgressListener;
10
11 import com.owncloud.android.network.OwnCloudClientUtils;
12
13 import android.accounts.Account;
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 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
145 wdc.setDataTransferProgressListener(this);
146
147 /// download will be in a temporal file
148 File tmpFile = new File(getTemporalPath(mAccount.name) + mFilePath);
149
150 /// create status notification to show the download progress
151 mNotification = new Notification(R.drawable.icon, getString(R.string.downloader_download_in_progress_ticker), System.currentTimeMillis());
152 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
153 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
154 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, mTotalDownloadSize == -1);
155 mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), 0, tmpFile.getName()));
156 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
157 // TODO put something smart in the contentIntent below
158 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
159 mNotificationMngr.notify(R.string.downloader_download_in_progress_ticker, mNotification);
160
161
162 /// perform the download
163 tmpFile.getParentFile().mkdirs();
164 mDownloadsInProgress.put(buildRemoteName(mAccount.name, mRemotePath), tmpFile.getAbsolutePath());
165 File newFile = null;
166 try {
167 if (wdc.downloadFile(mRemotePath, tmpFile)) {
168 newFile = new File(getSavePath(mAccount.name) + mFilePath);
169 newFile.getParentFile().mkdirs();
170 boolean moved = tmpFile.renameTo(newFile);
171
172 if (moved) {
173 ContentValues cv = new ContentValues();
174 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, newFile.getAbsolutePath());
175 getContentResolver().update(
176 ProviderTableMeta.CONTENT_URI,
177 cv,
178 ProviderTableMeta.FILE_NAME + "=? AND "
179 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
180 new String[] {
181 mFilePath.substring(mFilePath.lastIndexOf('/') + 1),
182 mAccount.name });
183 downloadResult = true;
184 }
185 }
186 } finally {
187 mDownloadsInProgress.remove(buildRemoteName(mAccount.name, mRemotePath));
188 }
189
190
191 /// notify result
192 mNotificationMngr.cancel(R.string.downloader_download_in_progress_ticker);
193 int tickerId = (downloadResult) ? R.string.downloader_download_succeeded_ticker : R.string.downloader_download_failed_ticker;
194 int contentId = (downloadResult) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;
195 Notification finalNotification = new Notification(R.drawable.icon, getString(tickerId), System.currentTimeMillis());
196 finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
197 // TODO put something smart in the contentIntent below
198 finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
199 finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), tmpFile.getName()), finalNotification.contentIntent);
200 mNotificationMngr.notify(tickerId, finalNotification);
201
202 sendFinalBroadcast(downloadResult, (downloadResult)?newFile.getAbsolutePath():null);
203 }
204
205 /**
206 * Callback method to update the progress bar in the status notification.
207 */
208 @Override
209 public void transferProgress(long progressRate) {
210 mCurrentDownloadSize += progressRate;
211 int percent = (int)(100.0*((double)mCurrentDownloadSize)/((double)mTotalDownloadSize));
212 if (percent != mLastPercent) {
213 mNotification.contentView.setProgressBar(R.id.status_progress, 100, (int)(100*mCurrentDownloadSize/mTotalDownloadSize), mTotalDownloadSize == -1);
214 mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), percent, new File(mFilePath).getName()));
215 mNotificationMngr.notify(R.string.downloader_download_in_progress_ticker, mNotification);
216 }
217
218 mLastPercent = percent;
219 }
220
221
222 /**
223 * Sends a broadcast in order to the interested activities can update their view
224 *
225 * @param downloadResult 'True' if the download was successful
226 * @param newFilePath Absolute path to the download file
227 */
228 private void sendFinalBroadcast(boolean downloadResult, String newFilePath) {
229 Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
230 end.putExtra(EXTRA_DOWNLOAD_RESULT, downloadResult);
231 end.putExtra(ACCOUNT_NAME, mAccount.name);
232 end.putExtra(EXTRA_REMOTE_PATH, mRemotePath);
233 if (downloadResult) {
234 end.putExtra(EXTRA_FILE_PATH, newFilePath);
235 }
236 sendBroadcast(end);
237 }
238
239 }