9f480fc03931ae7d4f671863684d5deb1dfd4af9
[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 org.apache.commons.httpclient.methods.GetMethod;
6 import org.apache.commons.httpclient.methods.HeadMethod;
7
8 import android.accounts.Account;
9 import android.accounts.AccountManager;
10 import android.app.Notification;
11 import android.app.NotificationManager;
12 import android.app.PendingIntent;
13 import android.app.Service;
14 import android.content.Intent;
15 import android.os.Handler;
16 import android.os.HandlerThread;
17 import android.os.IBinder;
18 import android.os.Looper;
19 import android.os.Message;
20 import android.os.Process;
21 import android.util.Log;
22 import android.webkit.MimeTypeMap;
23 import android.widget.RemoteViews;
24 import android.widget.Toast;
25 import eu.alefzero.owncloud.R;
26 import eu.alefzero.owncloud.datamodel.FileDataStorageManager;
27 import eu.alefzero.owncloud.datamodel.OCFile;
28 import eu.alefzero.owncloud.files.interfaces.OnDatatransferProgressListener;
29 import eu.alefzero.webdav.WebdavClient;
30
31 public class FileUploader extends Service implements OnDatatransferProgressListener {
32
33 public static final String UPLOAD_FINISH_MESSAGE = "UPLOAD_FINISH";
34 public static final String EXTRA_PARENT_DIR_ID = "PARENT_DIR_ID";
35
36 public static final String KEY_LOCAL_FILE = "LOCAL_FILE";
37 public static final String KEY_REMOTE_FILE = "REMOTE_FILE";
38 public static final String KEY_ACCOUNT = "ACCOUNT";
39 public static final String KEY_UPLOAD_TYPE = "UPLOAD_TYPE";
40
41 public static final int UPLOAD_SINGLE_FILE = 0;
42 public static final int UPLOAD_MULTIPLE_FILES = 1;
43
44 private static final String TAG = "FileUploader";
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 int mTotalDataToSend, mSendData;
53 private int mCurrentIndexUpload, mPreviousPercent;
54 private int mSuccessCounter;
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 }
83
84 @Override
85 public int onStartCommand(Intent intent, int flags, int startId) {
86 if (!intent.hasExtra(KEY_ACCOUNT) && !intent.hasExtra(KEY_UPLOAD_TYPE)) {
87 Log.e(TAG, "Not enought data in intent provided");
88 return Service.START_NOT_STICKY;
89 }
90 mAccount = intent.getParcelableExtra(KEY_ACCOUNT);
91 mUploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
92 if (mUploadType == -1) {
93 Log.e(TAG, "Incorrect upload type provided");
94 return Service.START_NOT_STICKY;
95 }
96 if (mUploadType == UPLOAD_SINGLE_FILE) {
97 mLocalPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
98 mRemotePaths = new String[] { intent
99 .getStringExtra(KEY_REMOTE_FILE) };
100 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
101 mLocalPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
102 mRemotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
103 }
104
105 if (mLocalPaths.length != mRemotePaths.length) {
106 Log.e(TAG, "Remote paths and local paths are not equal!");
107 return Service.START_NOT_STICKY;
108 }
109
110 Message msg = mServiceHandler.obtainMessage();
111 msg.arg1 = startId;
112 mServiceHandler.sendMessage(msg);
113
114 return Service.START_NOT_STICKY;
115 }
116
117 public void run() {
118 String message;
119 if (mSuccessCounter == mLocalPaths.length) {
120 message = getString(R.string.uploader_upload_succeed);
121 } else {
122 message = getString(R.string.uploader_upload_failed);
123 if (mLocalPaths.length > 1)
124 message += " (" + mSuccessCounter + " / " + mLocalPaths.length + getString(R.string.uploader_files_uploaded_suffix) + ")";
125 }
126 Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
127 }
128
129 public void uploadFile() {
130 FileDataStorageManager storageManager = new FileDataStorageManager(mAccount, getContentResolver());
131
132 mTotalDataToSend = mSendData = mPreviousPercent = 0;
133
134 mNotification = new Notification(
135 eu.alefzero.owncloud.R.drawable.icon, "Uploading...",
136 System.currentTimeMillis());
137 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
138 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
139 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
140 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
141 // dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
142 // 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
143 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
144
145 mNotificationManager.notify(42, mNotification);
146
147 WebdavClient wc = new WebdavClient(mAccount, getApplicationContext());
148 wc.setDataTransferProgressListener(this);
149
150 for (int i = 0; i < mLocalPaths.length; ++i) {
151 File f = new File(mLocalPaths[i]);
152 mTotalDataToSend += f.length();
153 }
154
155 Log.d(TAG, "Will upload " + mTotalDataToSend + " bytes, with " + mLocalPaths.length + " files");
156
157 mSuccessCounter = 0;
158
159 for (int i = 0; i < mLocalPaths.length; ++i) {
160
161 String mimeType = null;
162 try {
163 mimeType = MimeTypeMap.getSingleton()
164 .getMimeTypeFromExtension(
165 mLocalPaths[i].substring(mLocalPaths[i]
166 .lastIndexOf('.') + 1));
167 } catch (IndexOutOfBoundsException e) {
168 Log.e(TAG, "Trying to find out MIME type of a file without extension: " + mLocalPaths[i]);
169 }
170 if (mimeType == null)
171 mimeType = "application/octet-stream";
172
173 mCurrentIndexUpload = i;
174 mRemotePaths[i] = getAvailableRemotePath(wc, mRemotePaths[i]);
175 if (mRemotePaths[i] != null && wc.putFile(mLocalPaths[i], mRemotePaths[i], mimeType)) {
176 mSuccessCounter++;
177 OCFile new_file = new OCFile(mRemotePaths[i]);
178 new_file.setMimetype(mimeType);
179 new_file.setFileLength(new File(mLocalPaths[i]).length());
180 new_file.setModificationTimestamp(System.currentTimeMillis());
181 new_file.setLastSyncDate(0);
182 new_file.setStoragePath(mLocalPaths[i]);
183 File f = new File(mRemotePaths[i]);
184 long parentDirId = storageManager.getFileByPath(f.getParent().endsWith("/")?f.getParent():f.getParent()+"/").getFileId();
185 new_file.setParentId(parentDirId);
186 storageManager.saveFile(new_file);
187
188 Intent end = new Intent(UPLOAD_FINISH_MESSAGE);
189 end.putExtra(EXTRA_PARENT_DIR_ID, parentDirId);
190 sendBroadcast(end);
191 }
192
193 }
194 mNotificationManager.cancel(42);
195 run();
196 }
197
198 /**
199 * Checks if remotePath does not exist in the server and returns it, or adds a suffix to it in order to avoid the server
200 * file is overwritten.
201 *
202 * @param string
203 * @return
204 */
205 private String getAvailableRemotePath(WebdavClient wc, String remotePath) {
206 Boolean check = wc.existsFile(remotePath);
207 if (check == null) { // null means fail
208 return null;
209 } else if (!check) {
210 return remotePath;
211 }
212
213 int pos = remotePath.lastIndexOf(".");
214 String suffix = "";
215 String extension = "";
216 if (pos >= 0) {
217 extension = remotePath.substring(pos+1);
218 remotePath = remotePath.substring(0, pos);
219 }
220 int count = 2;
221 while (check != null && check) {
222 suffix = " (" + count + ")";
223 if (pos >= 0)
224 check = wc.existsFile(remotePath + suffix + "." + extension);
225 else
226 check = wc.existsFile(remotePath + suffix);
227 count++;
228 }
229 if (check == null) {
230 return null;
231 } else if (pos >=0) {
232 return remotePath + suffix + "." + extension;
233 } else {
234 return remotePath + suffix;
235 }
236 }
237
238 @Override
239 public void transferProgress(long progressRate) {
240 mSendData += progressRate;
241 int percent = (int)(100*((double)mSendData)/((double)mTotalDataToSend));
242 if (percent != mPreviousPercent) {
243 String text = String.format("%d%% Uploading %s file", percent, new File(mLocalPaths[mCurrentIndexUpload]).getName());
244 mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, false);
245 mNotification.contentView.setTextViewText(R.id.status_text, text);
246 mNotificationManager.notify(42, mNotification);
247 }
248 mPreviousPercent = percent;
249 }
250 }