1e688b5e80e28e7f1a2cd64989a8478b4ae33b9f
[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 int mUploadType;
54 private Notification mNotification;
55 private int mTotalDataToSend, mSendData;
56 private int mCurrentIndexUpload, mPreviousPercent;
57 private int mSuccessCounter;
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 String message;
126 if (mSuccessCounter == mLocalPaths.length) {
127 message = getString(R.string.uploader_upload_succeed);
128 } else {
129 message = getString(R.string.uploader_upload_failed);
130 if (mLocalPaths.length > 1)
131 message += " (" + mSuccessCounter + " / " + mLocalPaths.length + getString(R.string.uploader_files_uploaded_suffix) + ")";
132 }
133 Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
134 }
135
136 public void uploadFile() {
137 String baseUrl = mAccountManager.getUserData(mAccount,
138 AccountAuthenticator.KEY_OC_BASE_URL), ocVerStr = mAccountManager
139 .getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);
140 OwnCloudVersion ocVer = new OwnCloudVersion(ocVerStr);
141 String webdav_path = AccountUtils.getWebdavPath(ocVer);
142 Uri ocUri = Uri.parse(baseUrl + webdav_path);
143 String username = mAccount.name.substring(0,
144 mAccount.name.lastIndexOf('@'));
145 String password = mAccountManager.getPassword(mAccount);
146 FileDataStorageManager storageManager = new FileDataStorageManager(mAccount, getContentResolver());
147
148 mTotalDataToSend = mSendData = mPreviousPercent = 0;
149
150 mNotification = new Notification(
151 eu.alefzero.owncloud.R.drawable.icon, "Uploading...",
152 System.currentTimeMillis());
153 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
154 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
155 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
156 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
157 // dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
158 // 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
159 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
160
161 mNotificationManager.notify(42, mNotification);
162
163 WebdavClient wc = new WebdavClient(ocUri);
164 wc.allowSelfsignedCertificates();
165 wc.setDataTransferProgressListener(this);
166 wc.setCredentials(username, password);
167
168 for (int i = 0; i < mLocalPaths.length; ++i) {
169 File f = new File(mLocalPaths[i]);
170 mTotalDataToSend += f.length();
171 }
172
173 Log.d(TAG, "Will upload " + mTotalDataToSend + " bytes, with " + mLocalPaths.length + " files");
174
175 mSuccessCounter = 0;
176
177 for (int i = 0; i < mLocalPaths.length; ++i) {
178
179 String mimeType;
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 mimeType = "application/octet-stream";
188 }
189
190 mCurrentIndexUpload = i;
191 if (wc.putFile(mLocalPaths[i], mRemotePaths[i], mimeType)) {
192 mSuccessCounter++;
193 OCFile new_file = new OCFile(mRemotePaths[i]);
194 new_file.setMimetype(mimeType);
195 new_file.setFileLength(new File(mLocalPaths[i]).length());
196 new_file.setModificationTimestamp(System.currentTimeMillis());
197 new_file.setLastSyncDate(0);
198 new_file.setStoragePath(mLocalPaths[i]);
199 File f = new File(mRemotePaths[i]);
200 long parentDirId = storageManager.getFileByPath(f.getParent().endsWith("/")?f.getParent():f.getParent()+"/").getFileId();
201 new_file.setParentId(parentDirId);
202 storageManager.saveFile(new_file);
203
204 Intent end = new Intent(UPLOAD_FINISH_MESSAGE);
205 end.putExtra(EXTRA_PARENT_DIR_ID, parentDirId);
206 sendBroadcast(end);
207 }
208
209 }
210 mNotificationManager.cancel(42);
211 run();
212 }
213
214 @Override
215 public void transferProgress(long progressRate) {
216 mSendData += progressRate;
217 int percent = (int)(100*((double)mSendData)/((double)mTotalDataToSend));
218 if (percent != mPreviousPercent) {
219 String text = String.format("%d%% Uploading %s file", percent, new File(mLocalPaths[mCurrentIndexUpload]).getName());
220 mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, false);
221 mNotification.contentView.setTextViewText(R.id.status_text, text);
222 mNotificationManager.notify(42, mNotification);
223 }
224 mPreviousPercent = percent;
225 }
226 }