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