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