Refactoring of WebdavClient creation and setup
[pub/Android/ownCloud.git] / src / com / owncloud / android / files / services / FileUploader.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.datamodel.FileDataStorageManager;
9 import com.owncloud.android.datamodel.OCFile;
10 import eu.alefzero.webdav.OnDatatransferProgressListener;
11 import com.owncloud.android.utils.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.Intent;
19 import android.os.Handler;
20 import android.os.HandlerThread;
21 import android.os.IBinder;
22 import android.os.Looper;
23 import android.os.Message;
24 import android.os.Process;
25 import android.util.Log;
26 import android.webkit.MimeTypeMap;
27 import android.widget.RemoteViews;
28 import com.owncloud.android.R;
29 import eu.alefzero.webdav.WebdavClient;
30
31 public class FileUploader extends Service implements OnDatatransferProgressListener {
32
33 public static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
34 public static final String EXTRA_PARENT_DIR_ID = "PARENT_DIR_ID";
35 public static final String EXTRA_UPLOAD_RESULT = "RESULT";
36 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
37 public static final String EXTRA_FILE_PATH = "FILE_PATH";
38
39 public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
40 public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
41 public static final String KEY_ACCOUNT = "ACCOUNT";
42 public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
43 public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
44
45 public static final int UPLOAD_SINGLE_FILE = 0;
46 public static final int UPLOAD_MULTIPLE_FILES = 1;
47
48 private static final String TAG = "FileUploader";
49
50 private NotificationManager mNotificationManager;
51 private Looper mServiceLooper;
52 private ServiceHandler mServiceHandler;
53 private Account mAccount;
54 private String[] mLocalPaths, mRemotePaths;
55 private int mUploadType;
56 private Notification mNotification;
57 private long mTotalDataToSend, mSendData;
58 private int mCurrentIndexUpload, mPreviousPercent;
59 private int mSuccessCounter;
60
61 /**
62 * Static map with the files being download and the path to the temporal file were are download
63 */
64 private static Map<String, String> mUploadsInProgress = Collections.synchronizedMap(new HashMap<String, String>());
65
66 /**
67 * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
68 */
69 public static boolean isUploading(Account account, String remotePath) {
70 return (mUploadsInProgress.get(buildRemoteName(account.name, remotePath)) != null);
71 }
72
73 /**
74 * Builds a key for mUplaodsInProgress from the accountName and remotePath
75 */
76 private static String buildRemoteName(String accountName, String remotePath) {
77 return accountName + remotePath;
78 }
79
80
81
82
83 @Override
84 public IBinder onBind(Intent arg0) {
85 return null;
86 }
87
88 private final class ServiceHandler extends Handler {
89 public ServiceHandler(Looper looper) {
90 super(looper);
91 }
92
93 @Override
94 public void handleMessage(Message msg) {
95 uploadFile();
96 stopSelf(msg.arg1);
97 }
98 }
99
100 @Override
101 public void onCreate() {
102 super.onCreate();
103 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
104 HandlerThread thread = new HandlerThread("FileUploaderThread",
105 Process.THREAD_PRIORITY_BACKGROUND);
106 thread.start();
107 mServiceLooper = thread.getLooper();
108 mServiceHandler = new ServiceHandler(mServiceLooper);
109 }
110
111 @Override
112 public int onStartCommand(Intent intent, int flags, int startId) {
113 if (!intent.hasExtra(KEY_ACCOUNT) && !intent.hasExtra(KEY_UPLOAD_TYPE)) {
114 Log.e(TAG, "Not enough information provided in intent");
115 return Service.START_NOT_STICKY;
116 }
117 mAccount = intent.getParcelableExtra(KEY_ACCOUNT);
118 mUploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
119 if (mUploadType == -1) {
120 Log.e(TAG, "Incorrect upload type provided");
121 return Service.START_NOT_STICKY;
122 }
123 if (mUploadType == UPLOAD_SINGLE_FILE) {
124 mLocalPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
125 mRemotePaths = new String[] { intent
126 .getStringExtra(KEY_REMOTE_FILE) };
127 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
128 mLocalPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
129 mRemotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
130 }
131
132 if (mLocalPaths.length != mRemotePaths.length) {
133 Log.e(TAG, "Different number of remote paths and local paths!");
134 return Service.START_NOT_STICKY;
135 }
136
137 Message msg = mServiceHandler.obtainMessage();
138 msg.arg1 = startId;
139 mServiceHandler.sendMessage(msg);
140
141 return Service.START_NOT_STICKY;
142 }
143
144
145 /**
146 * Core upload method: sends the file(s) to upload
147 */
148 public void uploadFile() {
149 FileDataStorageManager storageManager = new FileDataStorageManager(mAccount, getContentResolver());
150
151 mTotalDataToSend = mSendData = mPreviousPercent = 0;
152
153 /// prepare client object to send the request to the ownCloud server
154 WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
155 wc.setDataTransferProgressListener(this);
156
157 /// create status notification to show the upload progress
158 mNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_in_progress_ticker), System.currentTimeMillis());
159 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
160 RemoteViews oldContentView = mNotification.contentView;
161 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
162 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
163 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
164 // dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
165 // BUT an empty Intent is not a very elegant solution; something smart should happen when a user 'clicks' on an upload in the notification bar
166 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
167 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
168
169
170 /// perform the upload
171 File [] localFiles = new File[mLocalPaths.length];
172 for (int i = 0; i < mLocalPaths.length; ++i) {
173 localFiles[i] = new File(mLocalPaths[i]);
174 mTotalDataToSend += localFiles[i].length();
175 }
176 Log.d(TAG, "Will upload " + mTotalDataToSend + " bytes, with " + mLocalPaths.length + " files");
177 mSuccessCounter = 0;
178 for (int i = 0; i < mLocalPaths.length; ++i) {
179 String mimeType = null;
180 try {
181 mimeType = MimeTypeMap.getSingleton()
182 .getMimeTypeFromExtension(
183 mLocalPaths[i].substring(mLocalPaths[i]
184 .lastIndexOf('.') + 1));
185 } catch (IndexOutOfBoundsException e) {
186 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + mLocalPaths[i]);
187 }
188 if (mimeType == null)
189 mimeType = "application/octet-stream";
190 mCurrentIndexUpload = i;
191 long parentDirId = -1;
192 boolean uploadResult = false;
193 String availablePath = getAvailableRemotePath(wc, mRemotePaths[i]);
194 try {
195 File f = new File(mRemotePaths[i]);
196 parentDirId = storageManager.getFileByPath(f.getParent().endsWith("/")?f.getParent():f.getParent()+"/").getFileId();
197 if(availablePath != null) {
198 mRemotePaths[i] = availablePath;
199 mUploadsInProgress.put(buildRemoteName(mAccount.name, mRemotePaths[i]), mLocalPaths[i]);
200 if (wc.putFile(mLocalPaths[i], mRemotePaths[i], mimeType)) {
201 OCFile new_file = new OCFile(mRemotePaths[i]);
202 new_file.setMimetype(mimeType);
203 new_file.setFileLength(localFiles[i].length());
204 new_file.setModificationTimestamp(System.currentTimeMillis());
205 new_file.setLastSyncDate(0);
206 new_file.setStoragePath(mLocalPaths[i]);
207 new_file.setParentId(parentDirId);
208 storageManager.saveFile(new_file);
209 mSuccessCounter++;
210 uploadResult = true;
211 }
212 }
213 } finally {
214 mUploadsInProgress.remove(buildRemoteName(mAccount.name, mRemotePaths[i]));
215
216 /// notify upload (or fail) of EACH file to activities interested
217 Intent end = new Intent(UPLOAD_FINISH_MESSAGE);
218 end.putExtra(EXTRA_PARENT_DIR_ID, parentDirId);
219 end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult);
220 end.putExtra(EXTRA_REMOTE_PATH, mRemotePaths[i]);
221 end.putExtra(EXTRA_FILE_PATH, mLocalPaths[i]);
222 end.putExtra(ACCOUNT_NAME, mAccount.name);
223 sendBroadcast(end);
224 }
225
226 }
227
228 /// notify final result
229 if (mSuccessCounter == mLocalPaths.length) { // success
230 //Notification finalNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_succeeded_ticker), System.currentTimeMillis());
231 mNotification.flags ^= Notification.FLAG_ONGOING_EVENT; // remove the ongoing flag
232 mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
233 mNotification.contentView = oldContentView;
234 // TODO put something smart in the contentIntent below
235 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
236 if (mLocalPaths.length == 1) {
237 mNotification.setLatestEventInfo( getApplicationContext(),
238 getString(R.string.uploader_upload_succeeded_ticker),
239 String.format(getString(R.string.uploader_upload_succeeded_content_single), localFiles[0].getName()),
240 mNotification.contentIntent);
241 } else {
242 mNotification.setLatestEventInfo( getApplicationContext(),
243 getString(R.string.uploader_upload_succeeded_ticker),
244 String.format(getString(R.string.uploader_upload_succeeded_content_multiple), mSuccessCounter),
245 mNotification.contentIntent);
246 }
247 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification); // NOT AN ERROR; uploader_upload_in_progress_ticker is the target, not a new notification
248
249 } else {
250 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
251 Notification finalNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_failed_ticker), System.currentTimeMillis());
252 finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
253 // TODO put something smart in the contentIntent below
254 finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
255 if (mLocalPaths.length == 1) {
256 finalNotification.setLatestEventInfo( getApplicationContext(),
257 getString(R.string.uploader_upload_failed_ticker),
258 String.format(getString(R.string.uploader_upload_failed_content_single), localFiles[0].getName()),
259 finalNotification.contentIntent);
260 } else {
261 finalNotification.setLatestEventInfo( getApplicationContext(),
262 getString(R.string.uploader_upload_failed_ticker),
263 String.format(getString(R.string.uploader_upload_failed_content_multiple), mSuccessCounter, mLocalPaths.length),
264 finalNotification.contentIntent);
265 }
266 mNotificationManager.notify(R.string.uploader_upload_failed_ticker, finalNotification);
267 }
268
269 }
270
271 /**
272 * Checks if remotePath does not exist in the server and returns it, or adds a suffix to it in order to avoid the server
273 * file is overwritten.
274 *
275 * @param string
276 * @return
277 */
278 private String getAvailableRemotePath(WebdavClient wc, String remotePath) {
279 Boolean check = wc.existsFile(remotePath);
280 if (check == null) { // null means fail
281 return null;
282 } else if (!check) {
283 return remotePath;
284 }
285
286 int pos = remotePath.lastIndexOf(".");
287 String suffix = "";
288 String extension = "";
289 if (pos >= 0) {
290 extension = remotePath.substring(pos+1);
291 remotePath = remotePath.substring(0, pos);
292 }
293 int count = 2;
294 while (check != null && check) {
295 suffix = " (" + count + ")";
296 if (pos >= 0)
297 check = wc.existsFile(remotePath + suffix + "." + extension);
298 else
299 check = wc.existsFile(remotePath + suffix);
300 count++;
301 }
302 if (check == null) {
303 return null;
304 } else if (pos >=0) {
305 return remotePath + suffix + "." + extension;
306 } else {
307 return remotePath + suffix;
308 }
309 }
310
311
312 /**
313 * Callback method to update the progress bar in the status notification.
314 */
315 @Override
316 public void transferProgress(long progressRate) {
317 mSendData += progressRate;
318 int percent = (int)(100*((double)mSendData)/((double)mTotalDataToSend));
319 if (percent != mPreviousPercent) {
320 String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, new File(mLocalPaths[mCurrentIndexUpload]).getName());
321 mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, false);
322 mNotification.contentView.setTextViewText(R.id.status_text, text);
323 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
324 }
325 mPreviousPercent = percent;
326 }
327 }