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