Uploading files are protected against removal from other apps
[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 long size = localFiles[i].length();
224 parentDirId = storageManager.getFileByPath(f.getParent().endsWith("/")?f.getParent():f.getParent()+"/").getFileId();
225 if(availablePath != null) {
226 mRemotePaths[i] = availablePath;
227 mUploadsInProgress.put(buildRemoteName(mAccount.name, mRemotePaths[i]), mLocalPaths[i]);
228 if (wc.putFile(mLocalPaths[i], mRemotePaths[i], mimeType)) {
229 OCFile new_file = new OCFile(mRemotePaths[i]);
230 new_file.setMimetype(mimeType);
231 new_file.setFileLength(size);
232 new_file.setModificationTimestamp(System.currentTimeMillis());
233 new_file.setLastSyncDate(0);
234 new_file.setStoragePath(mLocalPaths[i]);
235 new_file.setParentId(parentDirId);
236 if (force_override)
237 new_file.setKeepInSync(true);
238 storageManager.saveFile(new_file);
239 mSuccessCounter++;
240 uploadResult = true;
241 }
242 }
243 } finally {
244 mUploadsInProgress.remove(buildRemoteName(mAccount.name, mRemotePaths[i]));
245
246 /// notify upload (or fail) of EACH file to activities interested
247 Intent end = new Intent(UPLOAD_FINISH_MESSAGE);
248 end.putExtra(EXTRA_PARENT_DIR_ID, parentDirId);
249 end.putExtra(EXTRA_UPLOAD_RESULT, uploadResult);
250 end.putExtra(EXTRA_REMOTE_PATH, mRemotePaths[i]);
251 end.putExtra(EXTRA_FILE_PATH, mLocalPaths[i]);
252 end.putExtra(ACCOUNT_NAME, mAccount.name);
253 sendBroadcast(end);
254 }
255
256 }
257
258 /// notify final result
259 if (mSuccessCounter == mLocalPaths.length) { // success
260 //Notification finalNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_succeeded_ticker), System.currentTimeMillis());
261 mNotification.flags ^= Notification.FLAG_ONGOING_EVENT; // remove the ongoing flag
262 mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
263 mNotification.contentView = oldContentView;
264 // TODO put something smart in the contentIntent below
265 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
266 if (mLocalPaths.length == 1) {
267 mNotification.setLatestEventInfo( getApplicationContext(),
268 getString(R.string.uploader_upload_succeeded_ticker),
269 String.format(getString(R.string.uploader_upload_succeeded_content_single), localFiles[0].getName()),
270 mNotification.contentIntent);
271 } else {
272 mNotification.setLatestEventInfo( getApplicationContext(),
273 getString(R.string.uploader_upload_succeeded_ticker),
274 String.format(getString(R.string.uploader_upload_succeeded_content_multiple), mSuccessCounter),
275 mNotification.contentIntent);
276 }
277 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
278
279 } else {
280 mNotificationManager.cancel(R.string.uploader_upload_in_progress_ticker);
281 Notification finalNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_failed_ticker), System.currentTimeMillis());
282 finalNotification.flags |= Notification.FLAG_AUTO_CANCEL;
283 // TODO put something smart in the contentIntent below
284 finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
285 if (mLocalPaths.length == 1) {
286 finalNotification.setLatestEventInfo( getApplicationContext(),
287 getString(R.string.uploader_upload_failed_ticker),
288 String.format(getString(R.string.uploader_upload_failed_content_single), localFiles[0].getName()),
289 finalNotification.contentIntent);
290 } else {
291 finalNotification.setLatestEventInfo( getApplicationContext(),
292 getString(R.string.uploader_upload_failed_ticker),
293 String.format(getString(R.string.uploader_upload_failed_content_multiple), mSuccessCounter, mLocalPaths.length),
294 finalNotification.contentIntent);
295 }
296 mNotificationManager.notify(R.string.uploader_upload_failed_ticker, finalNotification);
297 }
298
299 }
300
301 /**
302 * Checks if remotePath does not exist in the server and returns it, or adds a suffix to it in order to avoid the server
303 * file is overwritten.
304 *
305 * @param string
306 * @return
307 */
308 private String getAvailableRemotePath(WebdavClient wc, String remotePath) {
309 Boolean check = wc.existsFile(remotePath);
310 if (check == null) { // null means fail
311 return null;
312 } else if (!check) {
313 return remotePath;
314 }
315
316 int pos = remotePath.lastIndexOf(".");
317 String suffix = "";
318 String extension = "";
319 if (pos >= 0) {
320 extension = remotePath.substring(pos+1);
321 remotePath = remotePath.substring(0, pos);
322 }
323 int count = 2;
324 while (check != null && check) {
325 suffix = " (" + count + ")";
326 if (pos >= 0)
327 check = wc.existsFile(remotePath + suffix + "." + extension);
328 else
329 check = wc.existsFile(remotePath + suffix);
330 count++;
331 }
332 if (check == null) {
333 return null;
334 } else if (pos >=0) {
335 return remotePath + suffix + "." + extension;
336 } else {
337 return remotePath + suffix;
338 }
339 }
340
341
342 /**
343 * Callback method to update the progress bar in the status notification.
344 */
345 @Override
346 public void transferProgress(long progressRate) {
347 mSendData += progressRate;
348 int percent = (int)(100*((double)mSendData)/((double)mTotalDataToSend));
349 if (percent != mPreviousPercent) {
350 String text = String.format(getString(R.string.uploader_upload_in_progress_content), percent, new File(mLocalPaths[mCurrentIndexUpload]).getName());
351 mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, false);
352 mNotification.contentView.setTextViewText(R.id.status_text, text);
353 mNotificationManager.notify(R.string.uploader_upload_in_progress_ticker, mNotification);
354 }
355 mPreviousPercent = percent;
356 }
357 }