OCFile stores again decoded remote paths; WebdavUtils.encode(...) added; fixed space...
[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
5 import android.accounts.Account;
6 import android.accounts.AccountManager;
7 import android.app.Notification;
8 import android.app.NotificationManager;
9 import android.app.PendingIntent;
10 import android.app.Service;
11 import android.content.Intent;
12 import android.os.Handler;
13 import android.os.HandlerThread;
14 import android.os.IBinder;
15 import android.os.Looper;
16 import android.os.Message;
17 import android.os.Process;
18 import android.util.Log;
19 import android.webkit.MimeTypeMap;
20 import android.widget.RemoteViews;
21 import android.widget.Toast;
22 import eu.alefzero.owncloud.R;
23 import eu.alefzero.owncloud.datamodel.FileDataStorageManager;
24 import eu.alefzero.owncloud.datamodel.OCFile;
25 import eu.alefzero.owncloud.files.interfaces.OnDatatransferProgressListener;
26 import eu.alefzero.webdav.WebdavClient;
27
28 public class FileUploader extends Service implements OnDatatransferProgressListener {
29
30 public static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
31 public static final String EXTRA_PARENT_DIR_ID = "PARENT_DIR_ID";
32
33 public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
34 public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
35 public static final String KEY_ACCOUNT = "ACCOUNT";
36 public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
37
38 public static final int UPLOAD_SINGLE_FILE = 0;
39 public static final int UPLOAD_MULTIPLE_FILES = 1;
40
41 private static final String TAG = "FileUploader";
42 private NotificationManager mNotificationManager;
43 private Looper mServiceLooper;
44 private ServiceHandler mServiceHandler;
45 private Account mAccount;
46 private String[] mLocalPaths, mRemotePaths;
47 private int mUploadType;
48 private Notification mNotification;
49 private int mTotalDataToSend, mSendData;
50 private int mCurrentIndexUpload, mPreviousPercent;
51 private int mSuccessCounter;
52
53 @Override
54 public IBinder onBind(Intent arg0) {
55 return null;
56 }
57
58 private final class ServiceHandler extends Handler {
59 public ServiceHandler(Looper looper) {
60 super(looper);
61 }
62
63 @Override
64 public void handleMessage(Message msg) {
65 uploadFile();
66 stopSelf(msg.arg1);
67 }
68 }
69
70 @Override
71 public void onCreate() {
72 super.onCreate();
73 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
74 HandlerThread thread = new HandlerThread("FileUploaderThread",
75 Process.THREAD_PRIORITY_BACKGROUND);
76 thread.start();
77 mServiceLooper = thread.getLooper();
78 mServiceHandler = new ServiceHandler(mServiceLooper);
79 }
80
81 @Override
82 public int onStartCommand(Intent intent, int flags, int startId) {
83 if (!intent.hasExtra(KEY_ACCOUNT) && !intent.hasExtra(KEY_UPLOAD_TYPE)) {
84 Log.e(TAG, "Not enought data in intent provided");
85 return Service.START_NOT_STICKY;
86 }
87 mAccount = intent.getParcelableExtra(KEY_ACCOUNT);
88 mUploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
89 if (mUploadType == -1) {
90 Log.e(TAG, "Incorrect upload type provided");
91 return Service.START_NOT_STICKY;
92 }
93 if (mUploadType == UPLOAD_SINGLE_FILE) {
94 mLocalPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
95 mRemotePaths = new String[] { intent
96 .getStringExtra(KEY_REMOTE_FILE) };
97 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
98 mLocalPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
99 mRemotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
100 }
101
102 if (mLocalPaths.length != mRemotePaths.length) {
103 Log.e(TAG, "Remote paths and local paths are not equal!");
104 return Service.START_NOT_STICKY;
105 }
106
107 Message msg = mServiceHandler.obtainMessage();
108 msg.arg1 = startId;
109 mServiceHandler.sendMessage(msg);
110
111 return Service.START_NOT_STICKY;
112 }
113
114 public void run() {
115 String message;
116 if (mSuccessCounter == mLocalPaths.length) {
117 message = getString(R.string.uploader_upload_succeed);
118 } else {
119 message = getString(R.string.uploader_upload_failed);
120 if (mLocalPaths.length > 1)
121 message += " (" + mSuccessCounter + " / " + mLocalPaths.length + getString(R.string.uploader_files_uploaded_suffix) + ")";
122 }
123 Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
124 }
125
126 public void uploadFile() {
127 FileDataStorageManager storageManager = new FileDataStorageManager(mAccount, getContentResolver());
128
129 mTotalDataToSend = mSendData = mPreviousPercent = 0;
130
131 mNotification = new Notification(
132 eu.alefzero.owncloud.R.drawable.icon, "Uploading...",
133 System.currentTimeMillis());
134 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
135 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
136 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
137 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
138 // dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
139 // 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
140 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
141
142 mNotificationManager.notify(42, mNotification);
143
144 WebdavClient wc = new WebdavClient(mAccount, getApplicationContext());
145 wc.setDataTransferProgressListener(this);
146
147 for (int i = 0; i < mLocalPaths.length; ++i) {
148 File f = new File(mLocalPaths[i]);
149 mTotalDataToSend += f.length();
150 }
151
152 Log.d(TAG, "Will upload " + mTotalDataToSend + " bytes, with " + mLocalPaths.length + " files");
153
154 mSuccessCounter = 0;
155
156 for (int i = 0; i < mLocalPaths.length; ++i) {
157
158 String mimeType = null;
159 try {
160 mimeType = MimeTypeMap.getSingleton()
161 .getMimeTypeFromExtension(
162 mLocalPaths[i].substring(mLocalPaths[i]
163 .lastIndexOf('.') + 1));
164 } catch (IndexOutOfBoundsException e) {
165 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + mLocalPaths[i]);
166 }
167 if (mimeType == null)
168 mimeType = "application/octet-stream";
169
170 mCurrentIndexUpload = i;
171 if (wc.putFile(mLocalPaths[i], mRemotePaths[i], mimeType)) {
172 mSuccessCounter++;
173 OCFile new_file = new OCFile(mRemotePaths[i]);
174 new_file.setMimetype(mimeType);
175 new_file.setFileLength(new File(mLocalPaths[i]).length());
176 new_file.setModificationTimestamp(System.currentTimeMillis());
177 new_file.setLastSyncDate(0);
178 new_file.setStoragePath(mLocalPaths[i]);
179 File f = new File(mRemotePaths[i]);
180 long parentDirId = storageManager.getFileByPath(f.getParent().endsWith("/")?f.getParent():f.getParent()+"/").getFileId();
181 new_file.setParentId(parentDirId);
182 storageManager.saveFile(new_file);
183
184 Intent end = new Intent(UPLOAD_FINISH_MESSAGE);
185 end.putExtra(EXTRA_PARENT_DIR_ID, parentDirId);
186 sendBroadcast(end);
187 }
188
189 }
190 mNotificationManager.cancel(42);
191 run();
192 }
193
194 @Override
195 public void transferProgress(long progressRate) {
196 mSendData += progressRate;
197 int percent = (int)(100*((double)mSendData)/((double)mTotalDataToSend));
198 if (percent != mPreviousPercent) {
199 String text = String.format("%d%% Uploading %s file", percent, new File(mLocalPaths[mCurrentIndexUpload]).getName());
200 mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, false);
201 mNotification.contentView.setTextViewText(R.id.status_text, text);
202 mNotificationManager.notify(42, mNotification);
203 }
204 mPreviousPercent = percent;
205 }
206 }