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