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