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