moving from eu.alefzero.eu to com.owncloud.android
[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.interfaces.OnDatatransferProgressListener;
11
12 import android.accounts.Account;
13 import android.app.Notification;
14 import android.app.NotificationManager;
15 import android.app.PendingIntent;
16 import android.app.Service;
17 import android.content.Intent;
18 import android.os.Handler;
19 import android.os.HandlerThread;
20 import android.os.IBinder;
21 import android.os.Looper;
22 import android.os.Message;
23 import android.os.Process;
24 import android.util.Log;
25 import android.webkit.MimeTypeMap;
26 import android.widget.RemoteViews;
27 import com.owncloud.android.R;
28 import eu.alefzero.webdav.WebdavClient;
29
30 public class FileUploader extends Service implements OnDatatransferProgressListener {
31
32 public static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
33 public static final String EXTRA_PARENT_DIR_ID = "PARENT_DIR_ID";
34 public static final String EXTRA_UPLOAD_RESULT = "RESULT";
35 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
36 public static final String EXTRA_FILE_PATH = "FILE_PATH";
37
38 public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
39 public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
40 public static final String KEY_ACCOUNT = "ACCOUNT";
41 public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
42 public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
43
44 public static final int UPLOAD_SINGLE_FILE = 0;
45 public static final int UPLOAD_MULTIPLE_FILES = 1;
46
47 private static final String TAG = "FileUploader";
48
49 private NotificationManager mNotificationManager;
50 private Looper mServiceLooper;
51 private ServiceHandler mServiceHandler;
52 private Account mAccount;
53 private String[] mLocalPaths, mRemotePaths;
54 private int mUploadType;
55 private Notification mNotification;
56 private long mTotalDataToSend, mSendData;
57 private int mCurrentIndexUpload, mPreviousPercent;
58 private int mSuccessCounter;
59
60 /**
61 * Static map with the files being download and the path to the temporal file were are download
62 */
63 private static Map<String, String> mUploadsInProgress = Collections.synchronizedMap(new HashMap<String, String>());
64
65 /**
66 * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
67 */
68 public static boolean isUploading(Account account, String remotePath) {
69 return (mUploadsInProgress.get(buildRemoteName(account.name, remotePath)) != null);
70 }
71
72 /**
73 * Builds a key for mUplaodsInProgress from the accountName and remotePath
74 */
75 private static String buildRemoteName(String accountName, String remotePath) {
76 return accountName + remotePath;
77 }
78
79
80
81
82 @Override
83 public IBinder onBind(Intent arg0) {
84 return null;
85 }
86
87 private final class ServiceHandler extends Handler {
88 public ServiceHandler(Looper looper) {
89 super(looper);
90 }
91
92 @Override
93 public void handleMessage(Message msg) {
94 uploadFile();
95 stopSelf(msg.arg1);
96 }
97 }
98
99 @Override
100 public void onCreate() {
101 super.onCreate();
102 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
103 HandlerThread thread = new HandlerThread("FileUploaderThread",
104 Process.THREAD_PRIORITY_BACKGROUND);
105 thread.start();
106 mServiceLooper = thread.getLooper();
107 mServiceHandler = new ServiceHandler(mServiceLooper);
108 }
109
110 @Override
111 public int onStartCommand(Intent intent, int flags, int startId) {
112 if (!intent.hasExtra(KEY_ACCOUNT) && !intent.hasExtra(KEY_UPLOAD_TYPE)) {
113 Log.e(TAG, "Not enough information provided in intent");
114 return Service.START_NOT_STICKY;
115 }
116 mAccount = intent.getParcelableExtra(KEY_ACCOUNT);
117 mUploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
118 if (mUploadType == -1) {
119 Log.e(TAG, "Incorrect upload type provided");
120 return Service.START_NOT_STICKY;
121 }
122 if (mUploadType == UPLOAD_SINGLE_FILE) {
123 mLocalPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
124 mRemotePaths = new String[] { intent
125 .getStringExtra(KEY_REMOTE_FILE) };
126 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
127 mLocalPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
128 mRemotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
129 }
130
131 if (mLocalPaths.length != mRemotePaths.length) {
132 Log.e(TAG, "Different number of remote paths and local paths!");
133 return Service.START_NOT_STICKY;
134 }
135
136 Message msg = mServiceHandler.obtainMessage();
137 msg.arg1 = startId;
138 mServiceHandler.sendMessage(msg);
139
140 return Service.START_NOT_STICKY;
141 }
142
143
144 /**
145 * Core upload method: sends the file(s) to upload
146 */
147 public void uploadFile() {
148 FileDataStorageManager storageManager = new FileDataStorageManager(mAccount, getContentResolver());
149
150 mTotalDataToSend = mSendData = mPreviousPercent = 0;
151
152 /// prepare client object to send the request to the ownCloud server
153 WebdavClient wc = new WebdavClient(mAccount, getApplicationContext());
154 wc.allowSelfsignedCertificates();
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 }